PicturesSpreadsheet
Floating pictures anchored to a cell, pictures placed in cells and the IMAGE function, in PNG, JPEG, GIF, BMP, TIFF, WebP, SVG, EMF and WMF, with alt text and xlsx round-trip.
Pictures float over the grid. Each one is anchored to a cell, so it moves with that cell when rows or columns are inserted, deleted, resized or hidden.
const logo = sheet.addImage({
src: 'data:image/png;base64,iVBORw0KGgo…',
alt: 'Northwind Traders logo',
anchor: { cell: 'A1', offsetX: 4, offsetY: 4, width: 160, height: 48 },
});src must be a data: URL or a blob: URL. The spreadsheet never loads pictures from the network, so remote URLs are refused with a console warning. To show a picture from a server, fetch it yourself and pass a data URL; that also lets it be saved into xlsx files.
Formats#
| Format | Shown | In xlsx files |
|---|---|---|
| PNG, JPEG, GIF, BMP | By the browser | Read and written |
| WebP, SVG | By the browser | Read and written; Excel needs a raster copy, see SVG and WebP pictures |
| TIFF | Decoded here to PNG for display: 1, 2, 4 and 8-bit grey and palette, 8-bit RGB and RGBA, stored in strips, uncompressed, LZW or PackBits | Read and written with the original bytes |
| EMF, WMF | Drawn here as SVG, see Windows metafiles | Read and written with the original bytes |
A TIFF outside that subset (Deflate, JPEG or CCITT compression, tiles, 16-bit samples) and a metafile that cannot be read are kept, moved and saved like any other picture, and shown as an empty dashed frame.
Windows metafiles#
Charts and diagrams pasted "as picture" from Office programs are usually EMF or WMF, which browsers do not display. The spreadsheet converts them to SVG for display and never changes the stored file.
The converter covers the records most such pictures use: lines, polylines, polygons and poly-polygons, rectangles and rounded rectangles, ellipses, arcs, pies and chords, Bézier curves, paths, text, pens, brushes and fonts, stretched bitmaps, saved device contexts, the window and viewport mapping and, in EMF, world transforms. Records outside that set are skipped and counted.
renderMetafile() gives you the same conversion, with the counts:
import { renderMetafile } from '@birchui/spreadsheet';
declare const bytes: Uint8Array;
const picture = renderMetafile(bytes);
if (picture) {
console.info(picture.format, picture.width, picture.height);
console.info(`${picture.shapeCount} shapes drawn, ${picture.skippedRecords} records skipped`);
document.body.insertAdjacentHTML('beforeend', picture.svg);
}Not drawn: clipping regions, raster operations other than plain copy, pattern and hatch brushes (drawn as a flat tint), EMF+ records (the EMF fallback that Office writes beside them is used), and text is laid out by the browser's fonts, so line widths can differ from the original.
Position and size#
A picture's anchor names the cell of its top left corner, an offset inside that cell and a size, all in pixels at 100 % zoom. Offsets and sizes may be fractions: a picture read from a file keeps the exact values of the file. editAs says what happens when the grid under the picture changes:
editAs |
Rows or columns inserted, deleted, resized or hidden before the picture | The same inside the picture |
|---|---|---|
| not set | The picture moves | The picture keeps its size |
'twoCell', with a to cell and offset for the bottom right corner |
The picture moves | The picture grows or shrinks with the cells |
'absolute', with x and y in sheet pixels |
The picture stays where it is | The picture keeps its size |
Pictures, charts, embedded files, shapes and slicers scale with the sheet zoom and scroll with the grid. With frozen panes each pane shows its own part of the sheet, so a picture that lies across the freeze line is cut there: the frozen part stays, the rest scrolls away under it. Split panes do the same.
rotation turns a picture clockwise around its centre, in degrees. flipH and flipV mirror it. crop hides a share of the picture on each side, as fractions of its width and height; the part that remains fills the anchor box. All four are read from and written to xlsx files.
Pictures, charts and shapes overlap in the order they have in the file. A workbook JSON can state that order in drawingOrder on the sheet, a list of ids from back to front; without it pictures are at the back, then charts, embedded files and shapes.
A picture that belongs to a group in an xlsx file is drawn where the group puts it and has a group value. It cannot be moved, resized or deleted, and the group is written back as it was.
Moving and resizing#
Click a picture to select it. Drag it to move it. Eight handles on its outline resize it, and Shift while dragging keeps its proportions; the round handle above it turns it, in steps of 15 degrees with Shift. Charts and embedded files have the eight handles but cannot be turned. With a picture selected, the arrow keys move it by one pixel, or ten with Shift, and Alt with the left and right arrow keys turns it by 15 degrees. Delete removes it and Escape returns the focus to the grid. Every change is undoable.
Ctrl+C or Ctrl+X on a selected picture or chart followed by Ctrl+V pastes a copy, at the active cell when the grid has the focus. A picture on the system clipboard, such as a screenshot, is pasted as a new picture at the active cell. Insert > Picture places a file at its natural size, scaled down only when it is larger than the visible grid, and selects it.
Pictures are fixed on read-only spreadsheets and on protected sheets, unless the sheet's protection allows editObjects.
Large pictures and many pictures#
Only the pictures that touch the visible panes have elements in the page. A picture whose data URL is longer than about 48,000 characters is shown through one object URL shared by every place that shows it; a picture of 1.5 megapixels or more is shown through a downscaled preview sized for the screen, made with createImageBitmap where the browser has it, and a sharper preview is made when you zoom in. The original bytes stay in the workbook and are what exportXlsx() writes. Object URLs are revoked when their pictures have been out of view for a while and when the spreadsheet is destroyed.
Pictures in code#
| Method | Purpose |
|---|---|
addImage(image, sheet?) |
Adds a picture and returns its id. |
updateImage(id, changes) |
Changes the source, anchor, size or alt text. |
removeImage(id) |
Deletes the picture. |
getImages(sheet?) |
Returns copies of a sheet's pictures. |
Pictures in cells#
Excel can place a picture inside a cell, so that it sorts, filters and moves with its row. These are read from and written to xlsx files, and drawn inside the cell, scaled to fit.
sheet.setCellImage('B2', { src: 'data:image/png;base64,iVBORw0KGgo…', alt: 'Brass desk lamp' });
sheet.getCellImage('B2');
sheet.setCellImage('B2', null);In the workbook JSON they are in cellImages on the sheet, keyed by cell address. As in Excel's files, the cell itself holds #VALUE!, which is what programs without this feature show; formulas that refer to the cell see that error. Set decorative for a picture screen readers should skip.
Delete on the cell removes the picture. Typing a value into the cell hides it and leaves it out of saved files; undo brings it back.
The IMAGE function#
=IMAGE(source, [alt_text], [sizing], [height], [width]) names a picture by web address. The spreadsheet makes no network requests, so by default the formula returns #BLOCKED!. To show such pictures, give the spreadsheet a resolveImage function that returns a data: or blob: URL for the addresses you trust:
import { createSpreadsheet } from '@birchui/spreadsheet';
declare const container: HTMLElement;
declare const logos: Map<string, string>;
createSpreadsheet(container, {
resolveImage: ({ source }) => logos.get(source),
});The function is called while formulas calculate, so it must answer at once from data you already hold; fetch and cache the pictures before you load the workbook. Returning undefined, or anything that is not a data: or blob: URL, leaves the cell at #BLOCKED!. The cell's value is the alternative text. sizing, height and width are checked and otherwise ignored: the picture is fitted to the cell.
createFormulaEngine() takes the same resolveImage option. With calculation: 'worker' the function cannot cross to the worker, so IMAGE returns #BLOCKED! there. In xlsx files the formula is written with #VALUE! as its stored result, which Excel replaces when it recalculates.
Accessibility#
Give every picture that carries meaning an alt text. Pictures are exposed as images named by alt, then name, then "Picture". Decorative pictures can keep an empty alt.
Excel files#
Pictures are saved into the xlsx package and read back from it, with their anchor and size, in every format above and always with their original bytes. A picture that was not edited is written back with the XML it had in the file, so its anchor values and everything this component does not model (outline, effects, locks) stay as they were; pictures that show the same bytes share one media part. See Excel files.
Pictures that are part of something else in a file are kept and written back without being shown: linked pictures, the sheet background, header and footer pictures, pictures used as the fill of a note, and pictures on form controls. Files stored in a workbook are covered in Embedded files.