runtime:images
Decode, transform and encode images. The chain is Bun.Image's: new Image(input), transforms that each return a new image, one output format, and an awaited terminal. Nothing is decoded until a terminal or metadata() is awaited, and the work runs off the event loop.
Bytes in and bytes out need nothing. A runtime:fs file() source needs FileRead and a file() destination FileWrite, checked and jailed as reading or writing that file would be. Status: Available.
Import
import { Image } from "runtime:images";
// Or the default aggregate:
import images from "runtime:images";new Image(input, options?)
input is a Uint8Array, an ArrayBuffer, any view, a Blob, or a runtime:fs file(). A path string is a TypeError: pass file(path). A SharedArrayBuffer or a resizable buffer is a TypeError. The bytes are copied when a terminal is called. The format is read from the bytes, never from a name.
| Option | Default | Effect |
|---|---|---|
maxPixels | 268402689 | Over this many pixels fails at the header with ERR_IMAGE_TOO_MANY_PIXELS, before allocation. Applies with nothing set; pass a number to lower or raise it. |
autoOrient | true | Apply the orientation the file declares; metadata() reports the upright size. |
toSrgb | true | Convert an embedded matrix/TRC ICC profile to sRGB. Off, keep the pixels and write the profile to outputs. |
animated | false | Every frame. Not yet supported: an animation with this set fails with ERR_IMAGE_FORMAT_UNSUPPORTED. Unset, an animation is its first frame. |
page | 0 | The page to open of a multi-page TIFF. Past the end, or past 0 for any other format, is a RangeError from the terminal. |
raw | — | Read input as raw pixels: { width, height, channels, depth? }, packed rows with no header. channels is 1 (grey), 2 (grey and alpha), 3 (RGB) or 4 (RGBA); depth is "uchar" (default), "ushort" or "float", and grey with alpha is 8-bit only. Bytes not exactly the layout's length are a RangeError from the terminal; maxPixels applies. premultiplied is a TypeError. |
new Image({ create: { width, height, channels, background } }) makes a canvas of one colour instead, as sharp's create does: channels is 3 or 4, background is required, and maxPixels applies. noise is a TypeError. A raw or created image's format is "raw", so it needs a format method to encode as anything else.
Transforms
Each returns a new Image and leaves the original unchanged.
| Method | Description |
|---|---|
resize(width, height?, options?) | Scale to a size. See Resize options. |
crop({ left, top, width, height }) | Keep a region. Outside the image is a RangeError from the terminal. |
rotate(degrees) | Clockwise, a multiple of 90. |
flip() / flop() | Mirror top to bottom / left to right. |
modulate({ brightness?, saturation?, hue?, lightness? }) | Multipliers (1 unchanged); hue in degrees; lightness added (0 unchanged). |
blur(sigma) | Gaussian, sigma in pixels. |
sharpen(amount = 1) | 3×3 sharpen. sharp's sharpen({ sigma, m1, m2, … }) is a TypeError. |
convolve({ width, height, kernel }) | Convolve with kernel, width × height numbers in row order; each side odd, at most 63. The result is divided by the kernel's sum, unless that is 0 (an edge detector). Edges repeat the nearest pixel. sharp's scale and offset are a TypeError. |
flatten({ background? }) | Draw over background (default black), drop alpha. |
grayscale() | Grey, keeping alpha: a one-channel image. |
greyscale() | Greyscale by luma, keeping the channel count. |
extractChannel(channel) | 0–3 or "red", "green", "blue", "alpha". A name the layout lacks is a RangeError from the terminal. |
negate({ alpha? }) | Invert every channel; alpha (default true) inverts alpha too. |
gamma(exponent) | Each channel becomes value^(1 / exponent). libvips' definition, not sharp's two arguments. |
linear(a, b?) | value * a + b per channel; each side a number or three. |
threshold(level = 128, { greyscale? }) | Two levels; greyscale (default true) thresholds luma. The channel count is kept, unlike sharp's. |
tint(color) | Tint towards color, keeping luma. |
recomb(matrix) | Mix channels through a 3×3 or 4×4 matrix. |
ensureAlpha(alpha = 1) | Add an alpha channel at alpha if there is none. |
removeAlpha() | Drop alpha without compositing. |
extend(n | { top?, right?, bottom?, left?, extendWith?, background? }) | Grow the canvas by n on every side, or by each margin given. extendWith fills the margin with "background" (default), "copy" (the edge, repeated), "repeat" or "mirror"; background defaults to opaque black, and a translucent one adds alpha. |
trim({ background?, threshold?, lineArt? }) | Cut away a border near background (default: the top-left pixel's colour), within threshold (default 10). lineArt keeps one-pixel lines. The chain before it runs in memory, so trim after shrinking. margin is a TypeError. |
composite(overlays) | Draw images over this one. See Composite. |
A colour is "#rgb", "#rgba", "#rrggbb", "#rrggbbaa", or { r, g, b, alpha } with alpha from 0 to 1.
Composite
composite([...overlays]) draws each overlay in order, the first lowest, as sharp's does. Each is an object:
| Option | Default | Description |
|---|---|---|
input | — | An Image (with its own chain and open options), or anything new Image takes, { create } included. A file() is read when the terminal is called, under FileRead. |
raw | — | Read input as raw pixels in this layout, as the raw open option. |
blend | "over" | One of sharp's modes: "clear", "source", "over", "in", "out", "atop", "dest", "dest-over", "dest-in", "dest-out", "dest-atop", "xor", "add", "saturate", "multiply", "screen", "overlay", "darken", "lighten", "colour-dodge", "colour-burn", "hard-light", "soft-light", "difference", "exclusion" ("color-dodge" and "color-burn" too). |
gravity | "center" | Where the overlay sits: the same nine names as position. |
left, top | — | Its top-left corner, in pixels; may be negative. They take precedence over gravity. Give both or neither. |
tile | false | Repeat it across the image, aligned by gravity or starting at left/top. |
The base and the overlays need not share a pixel format: an RGBA logo over an RGB photo stays RGB, and a mode that can erase ("clear", "dest-out", …) adds alpha. The bytes of every overlay are copied when the terminal is called, as the base's are.
const watermarked = await new Image(photo)
.composite([{ input: file("logo.png"), gravity: "southeast" }])
.jpeg()
.bytes();Resize options
resize(width, height?, options?) scales to width × height. Omit either side, or pass null, to keep the aspect ratio: resize(400) is 400 pixels wide at the image's own proportions.
| Option | Default | Description |
|---|---|---|
fit | "fill" | How the image meets the box. See below. |
filter | "lanczos3" | The resampling kernel. See below. |
background | transparent | The padding colour when fit is "contain". |
withoutEnlargement | false | Never make the image larger than it is. |
withoutReduction | false | Never make the image smaller than it is. |
position | "center" | Which part "cover" keeps and where "contain" places the image: "center", "north", "northeast", "east", "southeast", "south", "southwest", "west", "northwest" (sharp's aliases work too). "attention"/"entropy" are a TypeError. |
fit:
| Value | Result |
|---|---|
"fill" | Exactly width × height; the aspect ratio is not kept. |
"inside" | As large as fits inside the box, aspect ratio kept. |
"outside" | As small as covers the box, aspect ratio kept. |
"cover" | Fills the box, aspect ratio kept; the overflow is cropped, keeping the part position names (default the centre). |
"contain" | Fits inside the box, aspect ratio kept; the rest is padded with background, placed where position says (default the centre). |
filter:
| Value | Use |
|---|---|
"lanczos3" | Photographs. The sharpest. |
"lanczos2" | A little softer than "lanczos3", with less ringing. |
"mitchell" | Balanced sharpness and smoothness. |
"catmull-rom" | Bicubic. "cubic" is the same filter. |
"bilinear" | Fast, soft. "linear" is the same filter. |
"box" | Averages; fast downscaling. |
"nearest" | Keeps exact pixel values: pixel art, masks. |
Output formats
The last format method wins. Without one, the source's format. Never the destination's extension.
| Method | Options | Notes |
|---|---|---|
jpeg(options?) | quality 1–100 (80); progressive; chromaSubsampling "4:2:0" or "4:4:4" | Baseline unless progressive. Chroma is 4:2:0 below quality 90 and 4:4:4 from it unless given. Transparency is composited over black. |
png(options?) | compressionLevel 0–9; palette; colours (or colors) 2–256 (256); dither 0–1 (1), or a boolean | 8- or 16-bit, as the pixels are. colours or dither implies palette. progressive, quality and effort are a TypeError. |
webp(options?) | quality 1–100 (80); lossless; nearLossless; effort 0–6 (4); alphaQuality 0–100 (100) | Lossy by default. nearLossless is lossless with small changes quality allows. |
avif(options?) | quality 1–100 (80); chromaSubsampling ("4:2:0"); effort 0–9 (4) | 8-bit. Unlike sharp, 4:2:0 by default. lossless is a TypeError. |
gif(options?) | colours (or colors) 2–256; dither 0–1, or a boolean | One frame, palette-quantized. |
tiff() | — | |
raw(options?) | depth "uchar" (default), "ushort" or "float" | Packed pixels, no header, in the image's channels. metadata() of the same chain gives the width, height and channels. The Blob type is application/octet-stream. |
jxl(options?) | quality 1–100 (80); lossless | JPEG XL. Lossy (VarDCT) by default; an image with alpha is written lossless. distance and effort are a TypeError. |
Metadata in the output
EXIF and XMP are stripped from every output unless kept, which removes camera data and location from uploads. The ICC profile is always kept.
| Method | Effect |
|---|---|
keepExif() | Copy the source's EXIF into a JPEG, PNG, WebP, AVIF, TIFF or JPEG XL output. Once autoOrient has turned the pixels upright, its orientation says 1. |
keepXmp() | Copy the source's XMP. |
keepMetadata() | Both. |
withXmp(xmp) | Write the string xmp as the XMP packet, in place of the source's. |
withMetadata({ density? }) | Keep both, and write density (pixels per inch) as the resolution: JPEG's JFIF header, PNG's pHYs, TIFF's tags. orientation is a TypeError. |
Terminals
| Method | Resolves to |
|---|---|
metadata() | The image at this point in the chain, read from headers without decoding pixels. See Metadata. |
stats() | sharp's pixel statistics of the result: channels (each { min, max, sum, squaresSum, mean, stdev, minX, minY, maxX, maxY }, alpha included), isOpaque, entropy, sharpness and the dominant sRGB colour { r, g, b }. It runs the chain. |
bytes() | The encoded image, a Uint8Array. |
blob() | A Blob whose type is the format's media type (image/webp, image/jxl, …). |
write(destination) | Encodes into destination, a runtime:fs file(), and resolves to the number of bytes written. A path string is a TypeError. |
Metadata
metadata() reports width, height, pixelFormat, channels and hasAlpha as the chain leaves them: new Image(x).resize(400).metadata() reports the resized size. Everything else is what the source file says about itself, under sharp's names, and a field the file does not state is absent.
| Field | Description |
|---|---|
format | The source's: "jpeg", "png", "webp", "avif", "gif", "tiff", "jxl", or "raw" for raw and created input. |
pixelFormat | "gray8", "gray16", "graya8", "rgb8", "rgba8", "rgb16", "rgba16", "rgbf32" or "rgbaf32". |
animation | { frames, loop, durations } (milliseconds per frame), or null for a still. |
pages | Pages in the source document; 1 except for TIFF. |
trimOffsetLeft, trimOffsetTop | After a trim: minus the left and top of the box kept, as sharp reports them. |
orientation | The EXIF orientation, 1–8. |
bitsPerSample | Bits per stored sample, which may be fewer than the pixel format holds (a 4-bit PNG). |
density, resolutionUnit | Pixels per inch, and "inch" or "cm" as the file states it. |
isProgressive, isPalette | Progressive JPEG or interlaced PNG/GIF; samples index a palette. |
chromaSubsampling | JPEG and AVIF: "4:2:0", "4:4:4", … |
background | The colour a PNG or GIF names: { r, g, b } or { gray }, in the file's own samples. |
compression | The scheme, where a format has several. |
comments | [{ keyword, text }]: PNG text chunks, JPEG and GIF comments. |
hasProfile, icc, exif, xmp | Whether there is an ICC profile, and the ICC, EXIF and XMP bytes as Uint8Arrays. |
Errors
| Code / class | When |
|---|---|
ERR_IMAGE_DECODE_FAILED | The bytes are not a valid image of their format. |
ERR_IMAGE_FORMAT_UNSUPPORTED | An unknown format, or a valid file using something not implemented. |
ERR_IMAGE_TOO_MANY_PIXELS | Over maxPixels. |
TypeError / RangeError | A bad argument; from the method, or from the terminal when only the image shows it. |
Reading or writing a file() fails with the runtime:fs errors.
Moving from Bun.Image: see Migrating from Bun.