skip to content

With the Cloudflare Images binding, how does a Worker transform image bytes, and when is it a better fit than fetch()'s cf.image?

level: middleimportance: should knowfreq 22%

answer

  1. bytes in, not a URL
  2. input, transform, output, response
  3. output needs a MIME format
  4. info() to inspect first
  5. nothing is cached for you

basics

~10 s

The Images binding takes raw bytes: env.IMAGES.input(stream).transform({...}).output({ format: "image/webp" }), then .response(). It suits images with no public URL, such as uploads or private storage, and custom operation order; results are not cached automatically.

solid answer

~50 s

Declare `"images": { "binding": "IMAGES" }` in the Wrangler file. A chain starts with `env.IMAGES.input(stream)` (up to 20 MB from a request body, an R2 object, a `fetch()` body or a hosted image's `.bytes()`), adds one or more `.transform()` calls, optionally `.draw()` overlays, and ends with `.output({ format: "image/webp" })`, whose format is required; `.response()` turns the result into a `Response`, optionally with extra headers. `.info(stream)` returns format, size and dimensions, which is handy for rejecting a bad upload. Choose it over `cf.image` when the source has no public URL or when order matters: chained `.transform()` calls run in the order written, while the URL interface uses a fixed order. Binding responses are not cached automatically, so set `Cache-Control` and enable Workers Cache. Since July 2026 the binding is billed per unique transformation like URL transformations, and `.info()` is free.

code

javascript · 23 lines
javascript
export default {
  async fetch(request, env) {
    if (request.method !== "POST" || !request.body) {
      return new Response("POST an image", { status: 405 });
    }
    const [probe, pixels] = request.body.tee();
    let info;
    try {
      info = await env.IMAGES.info(probe);
    } catch (err) {
      return new Response(`not an image (${err.code})`, { status: 415 });
    }
    if (!("width" in info) || info.width > 8000) {
      return new Response("unsupported size", { status: 422 });
    }
    const result = await env.IMAGES.input(pixels)
      .transform({ width: 320, fit: "scale-down" })
      .output({ format: "image/webp", quality: 80 });
    return result.response({
      headers: { "Cache-Control": "public, max-age=86400" },
    });
  },
};

go deeper

for a junior

Recall the chain: input, one or more transform calls, output with a MIME format, then response, all through env.IMAGES.

for a middle

Explain when bytes beat URLs: uploads and private storage, ordered operations, overlays and text, and inspecting an upload with info() first.

for a senior

Show the production details: no automatic caching, Cache-Control through response(), the 20 MB input limit, error codes on ImagesError and local mock gaps.

for a principal

Decide where the binding belongs in a pipeline versus URL presets, and how per-unique billing and caching shape that split.

## What the binding is A **binding** connects a Worker to a Cloudflare resource through the `env` object instead of through an API token. The **Images binding** gives a Worker a programmable image processor that works on **raw bytes**. That is the key difference from `fetch()` with `cf.image` and from `/cdn-cgi/image/` URLs, which both need the source image to be reachable at a URL. ```json { "images": { "binding": "IMAGES" } } ``` ## The chain Every operation starts with a source method and ends with `.output()`: 1. `env.IMAGES.input(stream)` creates a handle from image bytes, at most **20 MB**: a request body, an R2 object's body, a `fetch()` response body, or a hosted image's bytes from `env.IMAGES.hosted.image(id).bytes()`. `env.IMAGES.text(content, options)` instead rasterizes a string, for a label or watermark. 2. `.transform({ width, height, fit, rotate, blur, ... })` applies parameters. Chain several to control order, for example rotate before flip; the URL interface applies `flip` before `rotate` and cannot be reordered. 3. `.draw(overlay, options)` composites another image or text handle, with options such as `opacity`, `repeat` and a side like `bottom`. 4. `.output({ format: "image/webp", quality: 80 })` encodes the result. `format` takes a MIME type and is required; there is no default output format. 5. `.response({ headers })` returns a `Response`. `Content-Type` always comes from the output format and cannot be overridden. Separately, **`.info(stream)`** reads `format`, `fileSize`, `width` and `height` without transforming anything. ## Binding or cf.image? | Situation | Better fit | |---|---| | Source has a public URL; you want automatic edge caching of derivatives | `cf.image` or the URL interface | | Source is a request body, an upload or a private bucket object | Images binding | | You need a specific operation order, overlays or rendered text | Images binding | | You must inspect dimensions or reject a non-image before storing it | Images binding (`.info()`) | For a marketplace, the binding fits the upload path: a seller posts a photo, the Worker calls `.info()` to reject non-images or absurd dimensions, makes a thumbnail with `.transform()`, and stores or returns it. Product pages that read originals from a public origin are a natural fit for `cf.image` presets. ## Overlays and ordered steps Ordering and overlays are where the binding earns its place over URL parameters. A watermark for a marketplace's zoom view is one chain: - `env.IMAGES.input(photo)` starts from the seller's original; - `.transform({ width: 1200 })` sizes it; - `.draw(env.IMAGES.input(logo).transform({ width: 100 }), { bottom: 10, right: 10, opacity: 0.5 })` places a resized logo 10 pixels in from the bottom-right corner at half opacity; - `.output({ format: "image/avif" })` encodes the composite. Setting both `left` and `right`, or both `top` and `bottom`, on one overlay is an error. `.text()` handles can be drawn the same way, up to 1,000 characters and 4096x4096 pixels of rendered text. ## Caching is your job Binding responses are **not cached automatically**. Every uncached call decodes and re-encodes the source, which adds latency and spends a transformation. The Images docs recommend: - enabling **Workers Cache** with a `cache` block (`enabled: true`) in the Wrangler file, so repeat requests are answered from cache without running the Worker; - passing `Cache-Control` through `.response({ headers })` to set how long the result stays cached. ## Billing, errors and local runs - **Billing.** Since 2026-07-01 binding calls are billed as **unique transformations**: each combination of source image and parameters counts once per calendar month, the same model as URL transformations. Before that, every call counted. `.info()` calls are not billed. - **Errors.** Failures throw an `ImagesError` with a numeric `code`; for example, code 9432 means the account still uses the legacy Image Resizing subscription, which does not support the binding. - **Local development.** `wrangler dev` runs a low-fidelity offline version that supports only `width`, `height`, `rotate` and `format`, at no charge; `wrangler dev --remote` uses the production service. The Workers Vitest integration uses the offline version by default. The snippet in this question ran under `wrangler dev`: a 400x300 PNG posted to it came back as a 320-pixel-wide WebP with the `Cache-Control` header set, and a text file was rejected before any transformation.

  • How do you resize a photo already stored in Cloudflare Images with the binding?
    Read its original bytes with `env.IMAGES.hosted.image(id).bytes()`, which returns a stream or `null` for a missing ID, and pass that stream to `env.IMAGES.input()`. This counts as a unique transformation, whereas serving the same image through its delivery URL and a variant counts toward Images Delivered.
  • Why might the binding's thumbnails look right locally but differ in production?
    `wrangler dev` uses a low-fidelity offline version that supports only `width`, `height`, `rotate` and `format`, so options such as `blur`, overlays or other `fit` modes may be ignored locally. Test them on a deployed Worker or under `wrangler dev --remote`.

  • Expecting Images binding responses to be cached at the edge automatically
  • Expecting wrangler dev to reproduce every binding option exactly
  • Thinking the binding needs the image at a public URL
  • Believing every repeated binding call is billed separately today
  • Assuming .info() calls cost a transformation

Assumes Cloudflare's platform as of 2026-10-10: since 2026-07-01 the Images binding is billed per unique transformation and .info() is free; before that, every binding call was billed.