Chaining and async
Image methods change the image in place and return it. Find out which calls are async and when to clone.
Jimp’s image methods work on the image you call them on: they change its pixels in place and return the same image, so calls can be chained.
Only the calls that read or write files and bytes are async.
Knowing these two rules tells you where to put await and when you need a copy.
Methods change the image
Calling a method such as resize or greyscale replaces the image’s pixels. There’s no undo:
import { Jimp } from "jimp";
const image = await Jimp.read("photo.jpg");
image.greyscale();
// `image` is now grey. The colors are gone.Each method also returns the image it was called on, not a new one:
const small = image.resize({ w: 100 });
small === image; // trueimage.width; // 100Chaining
Because every editing method returns the image, you can chain calls. Each one works on the result of the one before:
const image = await Jimp.read("photo.jpg");
image .resize({ w: 600 }) .crop({ x: 0, y: 0, w: 600, h: 400 }) .greyscale() .contrast(0.2);
await image.write("banner.jpg");That’s the same as writing each call on its own line. Order matters: blurring then resizing doesn’t give the same image as resizing then blurring. Build a chain step by step here, then try a different order:
image.pixelate(8)Docs →Pixelate the whole image, or only a region of it. Drag on the image to choose the region.
import { Jimp } from "jimp"; const image = await Jimp.read("dice.png"); // Click a method above to add it here await image.write("output.png");
Edits as data
apply runs the same kind of chain from a list, so edits can be stored as JSON or sent to a server or worker:
image.apply([ ["resize", { w: 600 }], ["crop", { x: 0, y: 0, w: 600, h: 400 }], ["greyscale"], ["contrast", 0.2],]);Keeping the original with clone
When you need the image before and after a change, call clone first and edit the copy:
const image = await Jimp.read("photo.jpg");
const thumbnail = image.clone().cover({ w: 150, h: 150 });const banner = image.clone().resize({ w: 1200 }).blur(4);
// `image` is unchangedawait Promise.all([ thumbnail.write("thumb.jpg"), banner.write("banner.jpg"), image.write("original.png"),]);Cloning copies every pixel, so clone once per version you need, not before every call.
What’s async
Anything that reads or writes encoded image data, fonts or files returns a promise. Everything else is synchronous.
Async: await these |
Returns |
|---|---|
Jimp.read(pathOrUrl) |
Promise<Jimp> |
Jimp.fromBuffer(buffer) |
Promise<Jimp> |
image.getBuffer(mime) |
Promise<Buffer> |
image.getBase64(mime) |
Promise<string> |
image.write(path) |
Promise<void> |
loadFont(file) |
Promise<font> |
These are synchronous, including two ways of creating an image:
new Jimp({ width, height })andJimp.fromBitmap(bitmap)cloneand every editing method:resize,crop,rotate,blur,color,composite,mask,print…- Every method that returns a value, and helper functions such as
intToRGBA,diffandmeasureText
So a typical program awaits at the start and the end, and nowhere in between:
import { Jimp, loadFont } from "jimp";import { SANS_32_WHITE } from "jimp/fonts";
const [image, font] = await Promise.all([Jimp.read("photo.jpg"), loadFont(SANS_32_WHITE)]);
image .cover({ w: 800, h: 400 }) .brightness(0.8) .print({ font, x: 20, y: 20, text: "Hello" });
const bytes = await image.getBuffer("image/jpeg", { quality: 85 });Chaining across await
A chain can start from a promise as long as you wrap the await, and it can end with an async call:
const bytes = await (await Jimp.read("photo.jpg")).resize({ w: 300 }).getBuffer("image/png");That works, but two statements are easier to read:
const image = await Jimp.read("photo.jpg");const bytes = await image.resize({ w: 300 }).getBuffer("image/png");Methods that return values
Some methods measure or inspect the image instead of changing it. They return a value, so they end a chain:
| Method | Returns |
|---|---|
getPixelColor(x, y) |
The pixel’s color as an RGBA number |
getPixelIndex(x, y) |
The pixel’s offset in image.bitmap.data |
hasAlpha() |
boolean |
autocropRect() |
{ x, y, w, h }: the area autocrop would keep |
hash(), pHash() |
A perceptual hash string |
distanceFromHash(pHash) |
A number from 0 (same) to 1 |
dominantColor() |
The main color as an RGBA number |
palette(count) |
{ color, weight }[]: the main colors, most common first |
scanIterator() |
An iterator over the pixels |
setPixelColor, scan and composite change the image and return it, like the other editing methods.
const image = await Jimp.read("photo.png");
const transparent = image.hasAlpha(); // a boolean, not the imageconst hash = image.greyscale().hash(); // a stringThe second line still changes image: it’s grey afterwards. Clone first if you only want the measurement: image.clone().greyscale().hash().
Processing many images
Each image is independent, so you can process several at the same time with Promise.all.
The image work itself runs on the main thread, though: the decoding, encoding and pixel operations don’t run in parallel.
For large batches, limit how many images you load at once to keep memory down.
import { Jimp } from "jimp";
const files = ["a.jpg", "b.jpg", "c.jpg"];
await Promise.all( files.map(async (file) => { const image = await Jimp.read(file); await image.resize({ w: 200 }).write(`thumbs/${file}`); }),);To run them in parallel, and keep the main thread free, use @jimp/worker.
It runs the same edits as apply in worker threads or, in the browser, web workers:
import { writeFile } from "node:fs/promises";import { availableParallelism } from "node:os";import { Worker } from "node:worker_threads";import { createJimpWorker } from "@jimp/worker";import type { Jimp } from "jimp";
const jimp = createJimpWorker<typeof Jimp>( () => new Worker(new URL("./jimp.worker.js", import.meta.url)), { concurrency: availableParallelism() },);
await Promise.all( files.map(async (file) => { const bytes = await jimp.run({ input: file, edits: [["resize", { w: 200 }]], output: { mime: "image/jpeg" }, }); await writeFile(`thumbs/${file}`, bytes); }),);jimp.worker.js is a two-line script that calls expose(Jimp); see Workers for setting it up.
Coming from v0
Jimp v0 took callbacks and had separate …Async methods. In v1:
Jimp.read,getBuffer,getBase64andwritereturn promises.getBufferAsync,getBase64AsyncandwriteAsyncare gone.- Methods no longer take a callback as their last argument.
- Methods take an options object instead of positional arguments, such as
resize({ w: 100 })instead ofresize(100, Jimp.AUTO).
See Migrate to v1 for the full list.
See also
- Reading and writing
- Errors and validation: what happens when a call fails
- Workers: running image work off the main thread
- Methods:
clone,apply,Jimp.read,getBuffer,write