Skip to content
docs
GitHub 4.5M /week v2.2.0
Guide

Using WEBP (And other WASM plugins)

Add WebP, AVIF, JPEG XL, JPEG 2000, SVG and faster JPEG and PNG codecs to Jimp with WASM format plugins.

The default build of Jimp only includes image formats written in JavaScript. WebP, AVIF, JPEG XL, JPEG 2000, SVG and other formats that have no JavaScript implementation come as WASM format plugins: codecs compiled to WebAssembly from C, C++ and Rust libraries, wrapped as Jimp format plugins. They aren’t part of jimp, so you add them to a custom Jimp.

Package MIME type What it does
@jimp/wasm-webp image/webp Reads and writes WebP.
@jimp/wasm-avif image/avif Reads and writes AVIF.
@jimp/wasm-jpeg image/jpeg Reads and writes JPEG with MozJPEG. Replaces @jimp/js-jpeg.
@jimp/wasm-png image/png Reads and writes PNG, and can shrink files with oxipng. Replaces @jimp/js-png.
@jimp/wasm-jxl image/jxl Reads and writes JPEG XL with libjxl. See JPEG XL.
@jimp/wasm-jpeg2000 image/jp2, image/j2c, image/jpx Reads and writes JPEG 2000 with OpenJPEG. See JPEG 2000.
@jimp/wasm-svg image/svg+xml Reads SVG by rendering it with resvg. See SVG.

The WASM plugins are ES modules only: import them with import, not require.

Adding WebP

  1. Install the plugin alongside jimp and @jimp/core:

    Terminal window
    npm install jimp @jimp/core @jimp/wasm-webp
  2. Create a Jimp with the default formats and plugins, plus WebP:

    jimp.ts
    import { createJimp } from "@jimp/core";
    import { defaultFormats, defaultPlugins } from "jimp";
    import webp from "@jimp/wasm-webp";
    // A custom jimp that supports webp
    export const Jimp = createJimp({
    formats: [...defaultFormats, webp],
    plugins: defaultPlugins,
    });
  3. Read and write WebP like any other format:

    index.ts
    import { Jimp } from "./jimp.js";
    // Read a WebP...
    const image = await Jimp.read("tree.webp");
    image.resize({ w: 160 });
    await image.write("tree-small.png");
    // ...or convert another format to WebP
    const photo = await Jimp.read("photo.jpg");
    await photo.write("photo.webp", { quality: 75 });

The codec is loaded the first time an image is decoded or encoded, so the first call takes a little longer.

Try it

This demo runs @jimp/wasm-webp in your browser. Change the options to re-encode the image, hold Compare to see the original, or upload a PNG, JPEG, GIF, BMP, TIFF or WebP to convert it.

WebP encoder
getBuffer("image/webp")

Encode the image as WebP. Upload any PNG, JPEG, GIF, BMP, TIFF or WebP file to convert it.

lossless
75
Loading the WebP codec…
WebP
index.js
import { createJimp } from "@jimp/core";import { defaultFormats, defaultPlugins } from "jimp";import webp from "@jimp/wasm-webp"; const Jimp = createJimp({  formats: [...defaultFormats, webp],  plugins: defaultPlugins,}); const image = await Jimp.read("tree.webp"); const webpBuffer = await image.getBuffer("image/webp", { quality: 75 });

WebP options

Pass these to write, getBuffer or getBase64 when writing image/webp. The most useful ones:

Option Type Default Description
quality number 100 0 to 100. For lossy images, higher means better quality and larger files. For lossless, it’s the effort spent compressing.
lossless 0 | 1 0 1 for lossless encoding.
method number 4 0 (fast) to 6 (slower, smaller files).
nearLossless number 100 0 to 100. Below 100, lossless encoding may change pixels slightly to save space.
alphaQuality number 100 0 to 100. Quality of the alpha channel.
exact 0 | 1 0 1 keeps the colors of fully transparent pixels, which the encoder otherwise changes to compress better.
index.ts
// Small lossy file
await image.write("small.webp", { quality: 60, method: 6 });
// Lossless
const buffer = await image.getBuffer("image/webp", { lossless: 1 });

The plugin accepts the options of libwebp’s WebPConfig that change the output, in camelCase; Formats lists them all. Invalid values throw a ZodError, for example quality: 150 fails with Too big: expected number to be <=100, and so do options the plugin doesn’t know. It also takes icc: an image with an ICC profile, such as a Display P3 photo, keeps it in the WebP unless you pass icc: false. See Color Spaces. WebP keeps transparency, and has no decode options.

The other WASM plugins

Each plugin is used the same way: install it, then add it to formats.

AVIF

jimp.ts
import { createJimp } from "@jimp/core";
import { defaultFormats, defaultPlugins } from "jimp";
import avif from "@jimp/wasm-avif";
export const Jimp = createJimp({
formats: [...defaultFormats, avif],
plugins: defaultPlugins,
});
const image = await Jimp.read("photo.jpg");
await image.write("photo.avif", { speed: 6 });

The encode options are quality (0 to 100, where 100 is lossless; it takes precedence over cqLevel), cqLevel, cqAlphaLevel, speed (default 6), subsample, tune, sharpness, denoiseLevel, chromaDeltaQ, tileColsLog2 and tileRowsLog2, from libavif. AVIF output has no ICC profile, so images in another color space are converted to sRGB first. In the browser, the AVIF encoder runs in a worker; see the Vite notes.

JPEG and PNG

@jimp/wasm-jpeg and @jimp/wasm-png replace the built-in JavaScript codecs with WebAssembly ones. MozJPEG usually produces smaller JPEGs at the same quality, and oxipng can shrink PNGs further. When two formats have the same MIME type Jimp uses the first one in the list, so put the WASM format before the defaults, or leave the JavaScript one out:

jimp.ts
import { createJimp } from "@jimp/core";
import { defaultFormats, defaultPlugins } from "jimp";
import jpeg from "@jimp/wasm-jpeg";
import png from "@jimp/wasm-png";
export const Jimp = createJimp({
formats: [jpeg, png, ...defaultFormats],
plugins: defaultPlugins,
});
await image.write("photo.jpg", { quality: 80, progressive: true });
await image.write("icon.png", { optimize: { level: 3 } });
  • @jimp/wasm-jpeg takes MozJPEG’s options, such as quality (default 75), progressive (default true) and optimizeCoding (default true). It also supports exif: true and icc, as the built-in JPEG format does.
  • @jimp/wasm-png takes an optimize object to run the output through oxipng: level (0 to 6, default 2), interlace (default false) and optimiseAlpha (default false). Each field is optional, so optimize: { level: 3 } works. Without optimize, the PNG isn’t optimized. It also takes icc, as the built-in PNG format does.

Each plugin’s source lists every option with its range and default.

JPEG XL

@jimp/wasm-jxl reads and writes JPEG XL with libjxl, compiled to WebAssembly by jSquash. JPEG XL has lossy and lossless modes, and keeps transparency.

npm install @jimp/core @jimp/wasm-jxl
jimp.ts
import { createJimp } from "@jimp/core";
import { defaultFormats, defaultPlugins } from "jimp";
import jxl from "@jimp/wasm-jxl";
export const Jimp = createJimp({
formats: [...defaultFormats, jxl],
plugins: defaultPlugins,
});
const image = await Jimp.read("photo.jxl");
await image.write("visually-lossless.jxl");
await image.write("lossless.jxl", { lossless: true });
await image.write("smaller.jxl", { quality: 75, effort: 9 });
Option Used when Default Description
quality writing 90 0 to 100. 90 is visually lossless for most images, and 100 is lossless.
lossless writing false Store every pixel exactly, including alpha. quality is ignored.
effort writing 7 1 (fastest) to 9 (slowest, smallest files).
progressive writing false Order the data so a partly downloaded file can be shown at a lower quality first. Makes files a little larger.
lossyModular writing false Use the modular mode for lossy images too, instead of VarDCT. It can do better on graphics, and worse on photos.
epf writing -1 Strength of the edge-preserving filter applied when decoding lossy images, 0 (off) to 3. -1 picks one from the quality.
decodingSpeedTier writing 0 0 to 4. Higher makes lossy images faster to decode, and larger.
photonNoiseIso writing 0 Add synthetic film grain to lossy images, like a photo taken at this ISO. 0 adds none.
maxResolutionInMP reading 100 Reject images larger than this many megapixels, before decoding them.

Decode options go under the MIME type, for example Jimp.read("photo.jxl", { "image/jxl": { maxResolutionInMP: 24 } }). Numbers outside their range are clamped. Options the plugin doesn’t know throw a ZodError.

  • Reading: bare codestreams and files in the JPEG XL container, including recompressed JPEGs. Grayscale and RGB images, with or without alpha and at any bit depth, are decoded to 8 bits per channel. Images in another color space, or with an ICC profile, are converted to sRGB, so they read as colorSpace: "srgb" with no iccProfile. Animations load only their first frame.
  • HDR: images with the PQ or HLG transfer function throw, because the codec would convert them to 8-bit sRGB without tone mapping and they would come out too dark. A PQ image throws Unsupported JPEG XL image: HDR images (with the PQ transfer function) can't be decoded, because the codec would convert them to 8-bit sRGB without tone mapping.
  • Writing: 8-bit sRGB with alpha, as a bare codestream. Images in another color space are converted to sRGB first. Lossy encoding compresses alpha too, but at the default quality fully transparent and fully opaque pixels stay that way.
  • Lossless round trips: lossless files store every pixel exactly, but this decoder can read a few color samples 1 off, because it decodes in floating point. Alpha is always exact. Other decoders, such as djxl and browsers, read the exact pixels.
  • Memory: the codec has at most 2 GB of memory, which is enough for about 40 megapixels lossless or 60 megapixels lossy. Larger images throw an error such as Failed to decode the 7000x7000 JPEG XL image: the codec ran out of memory. Lower maxResolutionInMP to reject them before decoding.
  • Size: the decoder’s wasm is about 850 KB (310 KB gzipped) and the encoder’s about 1.4 MB (510 KB gzipped). Each is loaded the first time an image is read or written. On cross-origin isolated pages, the browser encodes with a multi-threaded build.

Vite 8 and webpack 5 need no config. For Vite 7 and earlier, see Vite.

JPEG 2000

@jimp/wasm-jpeg2000 reads and writes JPEG 2000 with OpenJPEG, the format’s reference implementation. JPEG 2000 is common in scanning, archiving, medical imaging and PDF files. It has three exports, one per MIME type. Add the ones you need:

Export MIME type Files Read Write
jpeg2000 image/jp2 .jp2 yes yes
j2c image/j2c .j2c, .j2k yes yes
jpx image/jpx .jpx, .jpf yes no
jimp.ts
import { createJimp } from "@jimp/core";
import { defaultFormats, defaultPlugins } from "jimp";
import jpeg2000, { j2c, jpx } from "@jimp/wasm-jpeg2000";
export const Jimp = createJimp({
formats: [...defaultFormats, jpeg2000, j2c, jpx],
plugins: defaultPlugins,
});
const image = await Jimp.read("scan.jp2");
await image.write("lossless.jp2");
await image.write("smaller.jp2", { compressionRatio: 20 });
// Raw codestreams have no extension write() knows, so use getBuffer
const codestream = await image.getBuffer("image/j2c");
Option Used when Default Description
reduce reading 0 Decode at a lower resolution. Each step halves the width and height, without decoding the full image.
layers reading 0 Decode only the first quality layers, for a lower-quality preview. 0 decodes all of them.
maxResolutionInMP reading 100 Reject images larger than this many megapixels, after reduce, before decoding them.
compressionRatio writing 1 Target size as a ratio of the uncompressed RGB pixels, for example 20 for 20:1. 1 is lossless.
decompositions writing 5 Wavelet levels, which is how many times decoders can halve the image with reduce. Limited to what the image’s size allows.

Decode options go under the MIME type, for example Jimp.read("scan.jp2", { "image/jp2": { reduce: 2 } }). Out-of-range numbers are clamped or rounded rather than rejected.

  • Reading: grayscale and RGB images, including YCbCr with 4:2:0 or 4:2:2 chroma subsampling, with 1 to 16 bits per sample, scaled to 8 bits. An ICC profile in a JP2 or JPX file is read, so a Display P3 file reads as colorSpace: "display-p3".
  • No alpha: images with an alpha channel can’t be decoded, and throw Unsupported JPEG 2000 image with 4 components: only grayscale and RGB images can be decoded, without alpha.
  • Writing: 8-bit RGB without alpha or an ICC profile. Transparent pixels are drawn over image.background, and images in another color space are converted to sRGB. Writing JPX throws; write JP2 instead, which JPX readers can read too.
  • Size: the wasm is about 373 KB (131 KB gzipped), loaded the first time an image is read or written.

The codec’s JavaScript refers to Node’s fs and path, which webpack 5 tries to bundle for the browser. Turn them off:

webpack.config.js
export default {
resolve: { fallback: { fs: false, path: false } },
};

Vite 8 needs no config. For Vite 7 and earlier, see Vite.

SVG

@jimp/wasm-svg reads SVG files by rendering them to pixels with resvg. It can’t write SVG: write("image.svg") and getBuffer("image/svg+xml") throw Jimp can read SVG but can't write it. Write a raster format like PNG (image/png) instead.

jimp.ts
import { createJimp } from "@jimp/core";
import { defaultFormats, defaultPlugins } from "jimp";
import svg from "@jimp/wasm-svg";
export const Jimp = createJimp({
formats: [...defaultFormats, svg],
plugins: defaultPlugins,
});
// At the size the SVG sets
const logo = await Jimp.read("logo.svg");
// 512 pixels wide, keeping the aspect ratio, on white
const icon = await Jimp.read("logo.svg", {
"image/svg+xml": { width: 512, background: "white" },
});
await icon.write("icon.png");

SVG is recognized by its content, not its file name, so buffers, files, URLs and data: URLs all work. The image is sRGB and has an alpha channel: whatever the SVG doesn’t paint is transparent.

Option Default Description
width the SVG’s width Width in pixels. The height keeps the aspect ratio.
height the SVG’s height Height in pixels. The width keeps the aspect ratio. With width too, the image fits inside both.
scale 1 A multiple of the SVG’s size, for example 2 for twice the width and height. Can’t be combined with width or height.
background transparent A CSS color or 0xRRGGBBAA number to fill the image with behind the SVG.
fonts [] Font files (TTF, OTF, TTC or WOFF2) as Uint8Arrays or Buffers, to draw <text> with.
defaultFontFamily none The family for text without a font-family, and for the generic serif, sans-serif and monospace families.
maxResolutionInMP 100 Reject SVGs that would render larger than this many megapixels, before rendering them.
resolveImage none Loads the http: and https: images an SVG links to. Off by default; see the caution below.

The SVG’s size comes from its width and height attributes, or from its viewBox when it has neither. An SVG with neither is 100 × 100.

  • Text needs fonts. The plugin can’t use the system’s fonts, so <text> isn’t drawn unless you pass fonts. SVGs made for display usually convert text to paths, so this only matters for SVGs that keep it as text.
  • Nothing is fetched or read from disk. Images, stylesheets and fonts the SVG links to aren’t loaded. Images in data: URLs are drawn. That makes it safe to render SVGs you don’t trust, apart from the time a very complex SVG can take to render; render those in a worker you can stop.
  • Size: the wasm is about 2.5 MB (0.95 MB gzipped), loaded the first time an SVG is read. resvg is under the Mozilla Public License 2.0; the plugin itself is MIT.

Vite 8 and webpack 5 need no config. For Vite 7 and earlier, see Vite.

Node.js

The plugins work in Node.js 22 and later, like the rest of Jimp, without any setup: they read their .wasm files from node_modules. Use ES modules ("type": "module" in package.json, or .mjs files), as the plugins can’t be loaded with require.

Browser usage

Since you’re no longer using the pre-bundled version of jimp, your bundler has to handle the code written for Node.js. Jimp’s packages import Buffer from the buffer package, so you don’t need a Buffer polyfill (see Custom Jimp). In the browser the codecs fetch their .wasm files with new URL("*.wasm", import.meta.url), which webpack 5 and Vite’s production build handle without extra config. The one exception is @jimp/wasm-jpeg2000 with webpack 5, which needs the resolve.fallback setting.

Vite

Vite 7 and earlier need some config for the WASM plugins:

vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
// The @jsquash codecs load their wasm relative to their own files
optimizeDeps: {
exclude: [
"@jsquash/avif",
"@jsquash/jpeg",
"@jsquash/jxl",
"@jsquash/png",
"@jsquash/oxipng",
"@jsquash/webp",
],
},
// Needed for the multi-threaded encoders of @jimp/wasm-avif and @jimp/wasm-jxl
worker: { format: "es" },
});
  • optimizeDeps.exclude: Vite pre-bundles dependencies into node_modules/.vite/deps, which separates the codec code from the .wasm file it loads with new URL("*.wasm", import.meta.url). Without it, the dev server and vitest browser mode fail to load the wasm with errors like both async and sync fetching of the wasm failed or expected magic word 00 61 73 6d. Only the packages used by the plugins you install need to be listed (@jimp/wasm-png uses both @jsquash/png and @jsquash/oxipng).
  • worker.format: only needed for @jimp/wasm-avif and @jimp/wasm-jxl. Their encoders run in a worker and Vite’s default iife worker format can’t code-split, so vite build fails with Invalid value "iife" for option "worker.format" ("output.format" on Vite 5).

@jimp/wasm-jpeg2000 and @jimp/wasm-svg load their wasm the same way but have to be excluded themselves, with their CommonJS dependencies pre-bundled instead. Without this, the dev server fails with Failed to load the JPEG 2000 codec's wasm or Failed to load resvg's wasm:

vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
optimizeDeps: {
exclude: ["@jimp/wasm-jpeg2000", "@jimp/wasm-svg"],
include: [
"@jimp/wasm-jpeg2000 > @cornerstonejs/codec-openjpeg/wasmjs",
"@jimp/wasm-jpeg2000 > buffer",
"@jimp/wasm-svg > buffer",
],
},
});

List only the plugins you use. Vite 8 handles all of this on its own, so it doesn’t need any config.

Cloudflare Workers

The WASM plugins normally load their .wasm files with new URL("*.wasm", import.meta.url), which Workers can’t fetch. In Workers they fail with both async and sync fetching of the wasm failed.

Instead, import the .wasm files in your worker and pass them to the plugins with the wasm option. Wrangler turns each .wasm import into a precompiled WebAssembly.Module.

The .wasm files come from the @jsquash packages the plugins use, so install those too. This makes the imports resolve with any package manager, and keeps them on the same versions as the plugins’ own copies:

npm install @jimp/core @jimp/wasm-webp @jsquash/webp
src/index.ts
import { createJimp } from "@jimp/core";
import webp from "@jimp/wasm-webp";
import webpDecoder from "@jsquash/webp/codec/dec/webp_dec.wasm";
import webpEncoder from "@jsquash/webp/codec/enc/webp_enc_simd.wasm";
const Jimp = createJimp({
formats: [() => webp({ wasm: { decoder: webpDecoder, encoder: webpEncoder } })],
});
export default {
async fetch(request: Request) {
// Recompress the uploaded WebP
const image = await Jimp.read(await request.arrayBuffer());
return new Response(await image.getBuffer("image/webp", { quality: 50 }), {
headers: { "Content-Type": "image/webp" },
});
},
};

Each plugin’s default export is a function that takes options, so wrap it in an arrow function to pass them: formats expects functions it can call with no arguments. You only need to import the modules for what you use. For example, if a worker only decodes WebP, you can leave out the encoder.

Plugin Install wasm option
@jimp/wasm-avif @jsquash/avif decoder: @jsquash/avif/codec/dec/avif_dec.wasm
encoder: @jsquash/avif/codec/enc/avif_enc.wasm
@jimp/wasm-jpeg @jsquash/jpeg decoder: @jsquash/jpeg/codec/dec/mozjpeg_dec.wasm
encoder: @jsquash/jpeg/codec/enc/mozjpeg_enc.wasm
@jimp/wasm-jxl @jsquash/jxl decoder: @jsquash/jxl/codec/dec/jxl_dec.wasm
encoder: @jsquash/jxl/codec/enc/jxl_enc.wasm
@jimp/wasm-png @jsquash/png, @jsquash/oxipng png: @jsquash/png/codec/pkg/squoosh_png_bg.wasm
optimise: @jsquash/oxipng/codec/pkg/squoosh_oxipng_bg.wasm, only used with the optimize export option
@jimp/wasm-webp @jsquash/webp decoder: @jsquash/webp/codec/dec/webp_dec.wasm
encoder: @jsquash/webp/codec/enc/webp_enc_simd.wasm

Each codec is set up once, by the first image that uses it, so pass the same modules everywhere you create the plugin.

@jimp/wasm-jpeg2000 and @jimp/wasm-svg take a precompiled module the same way: jpeg2000({ wasm: { codec } }) with @cornerstonejs/codec-openjpeg/wasm, and svg({ wasm: { resvg } }) with @resvg/resvg-wasm/index_bg.wasm. Use that wherever they can’t load their own .wasm file, such as with esbuild.

With TypeScript, declare the .wasm imports. @jsquash/png and @jsquash/oxipng ship their own types for their .wasm files, so those two need declarations of their own:

src/wasm.d.ts
declare module "*.wasm" {
const module: WebAssembly.Module;
export default module;
}
declare module "@jsquash/png/codec/pkg/squoosh_png_bg.wasm" {
const module: WebAssembly.Module;
export default module;
}
declare module "@jsquash/oxipng/codec/pkg/squoosh_oxipng_bg.wasm" {
const module: WebAssembly.Module;
export default module;
}

The .wasm files count towards your worker’s size limit. AVIF is the largest, at about 1.2 MB gzipped for the decoder and encoder together.

All WASM plugins

See Formats for how the WASM formats compare with the built-in ones, and for community format plugins such as HEIC.