Images

runtime:images decodes, transforms and encodes JPEG, PNG, WebP, AVIF, GIF, TIFF and JPEG XL. Work on bytes needs no capability.

A thumbnail

JavaScript
import { Image } from "runtime:images";

const thumb = await new Image(bytes)
  .resize(400, 400, { fit: "cover" })
  .webp({ quality: 80 })
  .bytes();

fit: "cover" fills the box and crops the overflow from the centre; "inside" keeps the whole image within it. Give one side to keep the aspect ratio: resize(400).

Untrusted uploads

A small file can declare an enormous image. Every image is limited to 268 megapixels by default, the same limit sharp and Bun use, and an image over it is refused at its header, before any memory is allocated. There is nothing to set; map the errors to responses:

JavaScript
import { serve } from "runtime:http";
import { Image } from "runtime:images";

serve({ port: 8080 }, async (request) => {
  const image = new Image(await request.bytes());
  try {
    const body = await image.resize(800).webp().bytes();
    return new Response(body, { headers: { "content-type": "image/webp" } });
  } catch (error) {
    if (error.code === "ERR_IMAGE_TOO_MANY_PIXELS") return new Response(null, { status: 413 });
    if (error.code === "ERR_IMAGE_DECODE_FAILED") return new Response(null, { status: 400 });
    if (error.code === "ERR_IMAGE_FORMAT_UNSUPPORTED") return new Response(null, { status: 415 });
    throw error;
  }
});

To accept less, or more, pass maxPixels:

JavaScript
new Image(bytes, { maxPixels: 40_000_000 });   // 40 MP, about a 7700×5200 photo

Location data goes with the rest of the EXIF: outputs drop it unless you chain keepExif().

Several sizes from one source

Every method returns a new image, so one source fans out:

JavaScript
import { Image } from "runtime:images";
import { file } from "runtime:fs";

const source = new Image(file("uploads/photo.jpg"));
await Promise.all([
  source.resize(320).webp().write(file("public/photo-320.webp")),
  source.resize(1280).webp().write(file("public/photo-1280.webp")),
  source.resize(1280).avif().write(file("public/photo-1280.avif")),
]);
Info

Reading a file() needs --allow-read and writing one --allow-write, as for any runtime:fs call. The output format is the method you chain, never the file's extension.

Size before work

metadata() reads the header only, and reports the size at any point in a chain:

JavaScript
const { width, height, format, animation } = await new Image(bytes).metadata();
const { width: w } = await new Image(bytes).resize(400).metadata();   // 400

An animated GIF or WebP is processed as its first frame; animation says how many frames there were, so you can decide to keep the original instead.

Beyond thumbnails

resize is one step among several — crop, rotate (multiples of 90°), flip/flop, modulate, blur, sharpen, flatten, grayscale and extractChannel all chain the same way — and blob() returns the result as a Blob typed with the format's media type:

JavaScript
const avatar = await new Image(bytes)
  .resize(512, 512, { fit: "cover" })
  .modulate({ saturation: 0.5 })
  .jpeg({ quality: 85 })
  .blob();   // Blob of type "image/jpeg"

The full method list is in the API reference.

Adjustments

Per-pixel adjustments chain like everything else — negate, gamma, linear, threshold, tint, greyscale, recomb, ensureAlpha and removeAlpha, with sharp's names:

JavaScript
const poster = await new Image(bytes)
  .resize(800, 800, { fit: "cover", position: "north" })
  .modulate({ lightness: 5 })
  .tint("#224488")
  .jpeg({ quality: 85 })
  .bytes();

position picks which part a "cover" keeps (or where a "contain" places the image): "center" (default), the edges and the corners. withoutReduction is withoutEnlargement's counterpart: never scale down. metadata() also reports pages — how many pages the source holds, for multi-page TIFF opened with new Image(bytes, { page: n }).

Watermarks

composite draws images over this one, the first lowest, with sharp's options. A logo in a corner:

JavaScript
import { file } from "runtime:fs";

const marked = await new Image(bytes)
  .resize(1600)
  .composite([{ input: file("brand/logo.png"), gravity: "southeast" }])
  .jpeg({ quality: 85 })
  .bytes();

An overlay is an Image or anything one takes, so it can be resized in its own chain: { input: new Image(logo).resize(200) }. tile: true repeats it across the image, and blend picks how it combines ("multiply", "screen", "soft-light", …).

Raw pixels

raw() gives the decoded pixels, packed with no header, for code that works on samples itself: a hash, a placeholder, a model's input. metadata() of the same chain gives the layout:

JavaScript
const image = new Image(bytes).resize(32, 32, { fit: "cover" });
const { width, height, channels } = await image.metadata();
const pixels = await image.raw().bytes();   // width * height * channels bytes

Pixels go back in with the raw option, and a blank canvas is { create: { width, height, channels, background } }:

JavaScript
const edited = new Image(pixels, { raw: { width, height, channels } }).png();
const card = new Image({ create: { width: 1200, height: 630, channels: 3, background: "#ffffff" } })
  .composite([{ input: logo, gravity: "center" }])
  .png();

Keeping camera data

Outputs drop EXIF and XMP. To keep them, for a photo archive rather than a public upload:

JavaScript
const archived = await new Image(file("raw/photo.jpg")).keepMetadata().avif().bytes();

withMetadata({ density: 300 }) also writes a print resolution, and metadata() reports what a file carries: exif, xmp, icc, density, orientation and more.

Current limitations

Text rendering, rotation between the right angles, multi-frame output and a HEIC codec are not there yet. What that means next to sharp, Bun.Image and Deno's createImageBitmap is measured row by row on the comparison page.

Last updated on
Edit this page