Using in Browser
Use Jimp in the browser with a bundler or a CDN, with uploads, canvas, fonts and workers.
Jimp runs in the browser with the same API as in Node.js.
The jimp package includes a pre-bundled browser build with everything it needs, so there’s nothing to polyfill or configure.
Every playground on this site runs Jimp in your browser. Upload your own image to try it: nothing leaves your computer. The code panel shows browser code; switch it to Node to compare.
image.greyscale()Docs →Remove all color, keeping the perceived brightness of each pixel.
This method has no options.
import { Jimp } from "jimp"; const image = await Jimp.read("dice.png"); // Click a method above to add it here document.querySelector("img").src = await image.getBase64("image/png");
Add Jimp to your page
Install the package and import it as usual:
npm install jimp import { Jimp } from "jimp";The jimp package has a browser export condition that points at its pre-bundled build.
Vite, webpack 5 and esbuild (with --platform=browser) pick it up automatically when they build for the browser. With Rollup, set browser: true in @rollup/plugin-node-resolve.
The build includes the Buffer polyfill and the browser versions of its dependencies, so you don’t need vite-plugin-node-polyfills, webpack fallback settings or a global Buffer.
The browser build at dist/browser/index.js is a self-contained ES module, so you can import it straight from a CDN without a bundler:
<img id="output" alt="" />
<script type="module"> import { Jimp } from "https://cdn.jsdelivr.net/npm/jimp@2/dist/browser/index.js";
const image = await Jimp.read("/images/photo.jpg");
image.greyscale();
document.querySelector("#output").src = await image.getBase64("image/png");</script>The same file is on unpkg at https://unpkg.com/jimp@2/dist/browser/index.js.
jimp@2 always loads the latest 2.x release. Pin an exact version, such as jimp@2.0.0, so an update never changes your page.
The jimp/fonts export isn’t part of the bundle and can’t be imported from a CDN. Load fonts by URL instead; see Fonts.
If you build a custom Jimp from @jimp/core and individual plugins, your bundler bundles those packages itself instead of using the pre-built file. See Using a custom Jimp outside of Node.js for what that needs.
Load images
From a URL
Jimp.read fetches a URL with fetch and decodes the response:
import { Jimp } from "jimp";
// On the same siteconst image = await Jimp.read("/images/photo.jpg");
// On another site, which must send CORS headersconst remote = await Jimp.read("https://example.com/photo.jpg");Images on other domains are subject to CORS: the server has to allow your page to read them, even though an <img> tag can show them without permission.
A failed fetch rejects with Could not load Buffer from URL: <url>, and an error status rejects with HTTP Status <status> for url <url>.
From a file input
A File from an <input type="file"> or a drop event is a Blob, so you can pass it to Jimp.fromBuffer or Jimp.read directly:
<input type="file" accept="image/*" id="picker" /><img id="output" alt="" />import { Jimp } from "jimp";
const picker = document.querySelector<HTMLInputElement>("#picker")!;const output = document.querySelector<HTMLImageElement>("#output")!;
picker.addEventListener("change", async () => { const file = picker.files?.[0]; if (!file) return;
const image = await Jimp.fromBuffer(file);
image.resize({ w: 600 }).greyscale();
output.src = await image.getBase64("image/jpeg", { quality: 80 });});Jimp.fromBuffer detects the format from the file’s contents, so it doesn’t matter what the file is called.
Passing a Blob directly was added in 2.0; with older versions, pass await file.arrayBuffer().
If the user picks a format Jimp can’t read, such as WebP, it rejects with Mime type image/webp does not support decoding. Add the format with a WASM plugin to support it.
Show and download the result
write can’t save files in the browser; it throws.
Encode the image instead:
getBase64returns a data URL you can use as an<img>src. It’s the simplest option for small images.getBufferreturns the encoded bytes as aBuffer, which is aUint8Array. Wrap them in aBlobfor an object URL, a download or an upload.
import { JimpMime } from "jimp";
const buffer = await image.getBuffer(JimpMime.png);const blob = new Blob([buffer], { type: JimpMime.png });
// Show itconst url = URL.createObjectURL(blob);document.querySelector<HTMLImageElement>("#output")!.src = url;
// Download itconst link = document.createElement("a");link.href = url;link.download = "edited.png";link.click();
// Or upload itawait fetch("/upload", { method: "POST", body: blob });Object URLs are cheaper than data URLs for large images. Call URL.revokeObjectURL(url) when you no longer need one.
Canvas and ImageData
Jimp images and canvas ImageData use the same pixel layout: one byte each for red, green, blue and alpha, row by row.
That makes moving pixels between them cheap.
-
Read the canvas pixels with
getImageDataand pass them toJimp.fromBitmap. UnlikeJimp.read,fromBitmapis synchronous. It copies the pixels, so theImageDataisn’t changed by later edits.main.ts import { Jimp } from "jimp";const canvas = document.querySelector<HTMLCanvasElement>("#canvas")!;const ctx = canvas.getContext("2d")!;const image = Jimp.fromBitmap(ctx.getImageData(0, 0, canvas.width, canvas.height)); -
Edit the image as usual.
main.ts image.invert(); -
Copy the pixels into a new
ImageDataand draw it back. Size the canvas first if the method changed the image’s size.main.ts const imageData = new ImageData(new Uint8ClampedArray(image.bitmap.data),image.width,image.height,);canvas.width = image.width;canvas.height = image.height;ctx.putImageData(imageData, 0, 0);
To get pixels from an <img> element or an ImageBitmap, draw it on a canvas with drawImage first, then read the canvas as above.
The image must be on the same site or served with CORS headers, or the canvas is “tainted” and getImageData throws.
fromBitmap checks that the data has exactly width * height * 4 bytes, as the ImageData constructor does, and throws otherwise.
To skip the copy in step 3, wrap the image’s own memory in the ImageData instead:
const { data } = image.bitmap;
const imageData = new ImageData( new Uint8ClampedArray(data.buffer, data.byteOffset, data.length), image.width, image.height,);See Colors and pixels for the bitmap layout and for reading and writing single pixels.
Fonts
The SANS_* constants in jimp/fonts are file paths for Node.js, so they don’t work in the browser.
In the browser, loadFont fetches the font by URL. A font is a .fnt file plus one or more .png pages, which are loaded from the same directory as the .fnt file.
You can host the bundled Open Sans fonts yourself. They’re in node_modules/@jimp/plugin-print/dist/fonts/open-sans/, one folder per size and color (open-sans-8-black to open-sans-128-white).
Copy the folders you need into your public directory, then load them by URL:
import { Jimp, loadFont } from "jimp";
const font = await loadFont("/fonts/open-sans-32-black/open-sans-32-black.fnt");
const image = new Jimp({ width: 320, height: 80, color: 0xffffffff });image.print({ font, x: 10, y: 20, text: "Hello, browser" });For a quick prototype you can load them from a CDN instead, as the @jimp/plugin-print package includes the font files:
const font = await loadFont( "https://cdn.jsdelivr.net/npm/@jimp/plugin-print@2/dist/fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt",);Your own BMFont fonts work the same way. See Text and fonts for printing, wrapping and measuring text.
TrueType, OpenType and WOFF fonts load by URL too, with loadTTF from jimp/load-ttf. Serve the font file from your site, or pass its bytes from a file input as an ArrayBuffer:
import { loadTTF } from "jimp/load-ttf";
const font = await loadTTF("/fonts/Inter-Regular.woff");
image.print({ font, size: 32, x: 10, y: 20, text: "Hello, browser" });loadTTF is a separate import so that its font parser is only in your bundle when you use it.
Web workers
Decoding, editing and encoding all run on the thread that calls them.
On the main thread a large image can freeze the page for a moment, so move the work into a web worker with @jimp/worker.
The worker script exposes your Jimp class:
import { Jimp } from "jimp";import { expose } from "@jimp/worker";
const exposed = expose(Jimp);
export type JimpWorkerApi = typeof exposed;The page starts workers and sends them tasks: an image, a list of edits in the format apply takes, and the format to encode the result to:
import { createJimpWorker } from "@jimp/worker";import type { JimpWorkerApi } from "./jimp.worker";
const jimp = createJimpWorker<JimpWorkerApi>(() => new Worker(new URL("./jimp.worker.ts", import.meta.url), { type: "module", }),);
picker.addEventListener("change", async () => { const bytes = await jimp.run({ input: picker.files![0]!, edits: [["resize", { w: 800 }], ["blur", 8]], output: { mime: "image/png" }, });
output.src = URL.createObjectURL(new Blob([bytes], { type: "image/png" }));});new Worker(new URL("./file", import.meta.url), { type: "module" }) is the pattern Vite and webpack 5 recognize to bundle the worker.
Because the page only imports the worker’s type, jimp is bundled into the worker and not into the page.
Jimp works in module workers, including loadFont.
See Workers for running tasks in parallel, cancelling them, getting Jimp images back, and avoiding copies of large images.
Performance tips
- Shrink first. Most methods take time proportional to the number of pixels. Call
resizeorscaleToFitbefore effects such asblurorgaussian, not after. - Use a worker for anything that takes more than a frame or two, as shown above.
- Reuse decoded images. Decoding is often the slowest step. Keep the decoded image and
cloneit for each variation instead of reading the file again. - Mind memory. A decoded image takes four bytes per pixel: a 24 megapixel photo needs about 96 MB, and every clone needs as much again. See Reading Large Images.