Writing Plugins
Add your own image methods and image formats to Jimp, then test and publish them.
Everything Jimp can do comes from plugins.
The jimp package is createJimp from @jimp/core called with a list of method plugins, such as @jimp/plugin-blur, and format plugins, such as @jimp/js-png.
You can write both kinds yourself, and they work exactly like the built-in ones.
This guide builds a method plugin with a vignette method step by step, then a format plugin, then covers typing, testing and publishing.
How plugins work
A method plugin is a plain object of functions. Each function takes the image as its first argument, followed by the arguments the user passes:
import type { JimpClass } from "@jimp/types";
export const methods = { myMethod<I extends JimpClass>(image: I, options: MyOptions) { // Change image.bitmap... return image; },};When you pass it to createJimp, every image gets a myMethod(options) method that calls methods.myMethod(image, options).
What the method returns decides how it behaves:
- An image: Jimp copies that image’s
bitmaponto the image the method was called on, and returns the image it was called on. The method changes the image in place and can be chained, likeresizeorblur. - Anything else: the value is returned as-is, like
hashreturning a string orgetPixelColorreturning a number.
A format plugin is a function that returns an object describing an image format: its MIME type, an encode function that turns pixels into file bytes, and a decode function that turns file bytes into pixels.
import type { Format } from "@jimp/types";
export default function myFormat() { return { mime: "image/x-my-format", encode: (bitmap, options) => { /* return a Buffer */ }, decode: (data, options) => { /* return { data, width, height } */ }, } satisfies Format<"image/x-my-format">;}Both kinds work with the image’s bitmap: { data, width, height }, where data is a Buffer with four bytes per pixel in RGBA order.
Colors and pixels explains the layout.
Write a method plugin
The vignette method darkens an image toward its edges.
-
Set up the package. A plugin needs
@jimp/typesfor the image type and, if it takes options, zod to validate them. Use@jimp/coreandjimpwhile developing and testing.Terminal window npm install @jimp/types zodnpm install --save-dev @jimp/core jimp vitest typescript -
Describe the options with a zod schema. Jimp’s own methods validate their options with zod, so invalid input fails with a clear error instead of a broken image. Infer the TypeScript type from the schema so the two never disagree.
src/index.ts import type { JimpClass, RGBAColor } from "@jimp/types";import { z } from "zod";const VignetteOptionsSchema = z.object({/** How dark the corners get, from 0 (unchanged) to 1 (black). */strength: z.number().min(0).max(1).optional(),});export type VignetteOptions = z.infer<typeof VignetteOptionsSchema>; -
Write the method. Parse the options, change the pixels in
image.bitmap, and return the image.image.scancalls a function for every pixel with its coordinates and its index inbitmap.data.src/index.ts export const methods = {/*** Darken the edges of the image.* @example* ```ts* image.vignette({ strength: 0.8 });* ```*/vignette<I extends JimpClass>(image: I, options: VignetteOptions = {}) {const { strength = 0.6 } = VignetteOptionsSchema.parse(options);const { width, height, data } = image.bitmap;const cx = (width - 1) / 2;const cy = (height - 1) / 2;const maxDistance = Math.hypot(cx, cy) || 1;image.scan((x, y, idx) => {const distance = Math.hypot(x - cx, y - cy) / maxDistance;const factor = 1 - strength * distance ** 2;data[idx] = Math.round(data[idx]! * factor);data[idx + 1] = Math.round(data[idx + 1]! * factor);data[idx + 2] = Math.round(data[idx + 2]! * factor);});return image;},}; -
Add a method that returns a value. A plugin can mix both kinds of method.
averageColorreturns anRGBAColor, so it ends a chain instead of continuing it. Add it to the samemethodsobject:src/index.ts /** Get the average color of the image. */averageColor<I extends JimpClass>(image: I): RGBAColor {const { data } = image.bitmap;const pixels = data.length / 4;const sum = { r: 0, g: 0, b: 0, a: 0 };image.scan((_, __, idx) => {sum.r += data[idx]!;sum.g += data[idx + 1]!;sum.b += data[idx + 2]!;sum.a += data[idx + 3]!;});return {r: Math.round(sum.r / pixels),g: Math.round(sum.g / pixels),b: Math.round(sum.b / pixels),a: Math.round(sum.a / pixels),};}, -
Use it. Build a Jimp class with the default plugins and formats plus yours:
jimp.ts import { createJimp } from "@jimp/core";import { defaultFormats, defaultPlugins } from "jimp";import { methods as vignette } from "jimp-plugin-vignette";export const Jimp = createJimp({formats: defaultFormats,plugins: [...defaultPlugins, vignette],});const image = await Jimp.read("photo.jpg");image.resize({ w: 400 }).vignette({ strength: 0.8 }).greyscale();console.log(image.averageColor()); // { r: 24, g: 24, b: 24, a: 75 }await image.write("vignette.png");
Conventions
The built-in plugins follow a few conventions. Following them makes your plugin feel like part of Jimp:
- Change the image and return it. Methods are expected to mutate the image they’re called on. If someone needs the original, they call
clonefirst. See Chaining and async. - Take one primitive or an options object. A method with a single, obvious argument takes it directly, like
blur(5)oropacity(0.5). Anything else takes one options object, likeresize({ w, h, mode }). - Validate with zod. Parse options with a schema at the top of the method, and export the inferred type (for example
VignetteOptions) so users can type their own code. - Stay synchronous. Image methods are synchronous in Jimp. Async work belongs in a separate function, as with
loadFont. - Add a JSDoc comment with an
@example. Editors show it when users hover over the method.
Changing the image’s size
When a method changes the size of the image, replace the whole bitmap, not just data:
import { Buffer } from "buffer";
// Inside a method: a copy with a transparent 10px borderconst pad = 10;const width = image.bitmap.width + pad * 2;const height = image.bitmap.height + pad * 2;const data = Buffer.alloc(width * height * 4);
image.scan((x, y, idx) => { image.bitmap.data.copy(data, ((y + pad) * width + x + pad) * 4, idx, idx + 4);});
image.bitmap = { data, width, height };return image;Buffer comes from the buffer package, as in Jimp’s own plugins, so the plugin works in browsers without a polyfill. In Node.js it resolves to the built-in Buffer.
Building on other methods and images
To reuse another plugin’s method, import its methods object and call the function directly with the image. This is how cover uses resize and crop:
import { methods as resizeMethods } from "@jimp/plugin-resize";
// Inside a methodimage = resizeMethods.resize(image, { w: 100 });Calling image.resize() inside a plugin would only work when the user’s Jimp happens to include @jimp/plugin-resize. Importing it makes the dependency explicit.
To work on a copy, use clone from @jimp/utils. To make a new blank image of the same class, call the image’s constructor:
import { clone } from "@jimp/utils";
const copy = clone(image);
// eslint-disable-next-line @typescript-eslint/no-explicit-anyconst canvas: I = new (image.constructor as any)({ width: image.bitmap.width, height: image.bitmap.height, color: 0x00000000,});
// Keep the image's color space, so drawing the image onto canvas doesn't convert itcanvas.iccProfile = image.iccProfile;You can return a different image from a method, such as canvas after drawing on it. Jimp copies its bitmap onto the image the method was called on, so the user still sees their own image change.
To draw shapes, such as lines, outlines or glyphs, import the rasterizer from @jimp/plugin-draw instead of setting pixels yourself. fillPath, strokePath and drawShape antialias edges, take the same colors and gradients as drawRect, and convert CSS colors to the image’s color space. See Drawing from plugins.
import { strokePath } from "@jimp/plugin-draw";
// Inside a method: underline the image with a 4-pixel rounded linestrokePath(image, `M 8 ${image.bitmap.height - 8} H ${image.bitmap.width - 8}`, options.color, { width: 4, cap: "round",});Color spaces
An image can be in a color space other than sRGB, such as Display P3; see Color Spaces. Pixel values are always in the image’s own color space, so most methods don’t need to do anything. Two cases do:
-
A method that takes a CSS color should convert it to the image’s color space, as
borderdoes. CSS colors are sRGB, so#ff0000is a different pixel value in a Display P3 image. Numbers are pixel values and aren’t converted.src/index.ts import { cssColorToHex, getColorSpace } from "@jimp/utils";// Inside a method: a pixel value for the user's color, in the image's spaceconst hex = cssColorToHex(options.color, getColorSpace(image)); -
A method that creates a new image and draws the original onto it should give the new image the original’s profile, as in the example above.
compositeandblitconvert a source in a different color space, so without the profile the original’s colors are converted to sRGB.
Write a format plugin
A format plugin teaches Jimp to read and write one MIME type.
It’s a function, not an object, so createJimp can create it once per Jimp class:
createJimp({ formats: [png, jpeg] }); // not png(), jpeg()| Property | Type | Description |
|---|---|---|
mime |
string |
The MIME type, such as "image/png". |
detect |
(data: Buffer) => boolean |
Optional. Return true if data is in this format. Only needed for formats file-type can’t recognize; see below. |
encode |
(bitmap: Bitmap, options?) => Buffer | Promise<Buffer> |
Turn RGBA pixels into file bytes. Receives the options passed to getBuffer, getBase64 or write. |
decode |
(data: Buffer, options?) => Bitmap | Promise<Bitmap> |
Turn file bytes into RGBA pixels. Receives this format’s entry from the decode options. |
hasAlpha |
boolean |
Set to true if the format stores transparency. Otherwise Jimp flattens the image onto image.background before calling encode. |
decodeFrames |
(data: Buffer, options?, { maxFrames? }) => DecodedFrames | Promise<DecodedFrames> |
Optional. Decode every frame or page, for Jimp.readFrames; see Animated formats. |
encodeFrames |
(frames: BitmapFrame[], options?) => Buffer | Promise<Buffer> |
Optional. Encode several frames, for Jimp.encodeFrames and Jimp.writeFrames. |
The bitmap returned by decode must have four bytes per pixel in RGBA order. Convert from the codec’s layout if it differs.
Change a built-in format
The simplest format plugin wraps an existing one.
This one changes the default JPEG quality from 100 to 80, and leaves everything else to @jimp/js-jpeg:
import jpeg, { type JPEGOptions } from "@jimp/js-jpeg";import type { Format } from "@jimp/types";
export default function jpeg80() { const base = jpeg();
return { ...base, encode: (bitmap, { quality = 80, ...options }: JPEGOptions = {}) => base.encode(bitmap, { quality, ...options }), } satisfies Format<"image/jpeg">;}When two formats have the same MIME type, Jimp uses the first one in the list, so put yours before the defaults:
import { createJimp } from "@jimp/core";import { defaultFormats, defaultPlugins } from "jimp";import jpeg80 from "./jpeg80.js";
const Jimp = createJimp({ formats: [jpeg80, ...defaultFormats], plugins: defaultPlugins,});
const image = await Jimp.read("photo.png");await image.write("photo.jpg"); // quality 80The exif JPEG option keeps working, as Jimp handles it for any image/jpeg format.
Add a new format
A new format usually wraps an existing codec library.
This template shows the shape; replace codec with the library you use:
import { Buffer } from "buffer";import type { Bitmap, Format } from "@jimp/types";import * as codec from "some-codec";
export interface MyEncodeOptions { quality?: number;}
export interface MyDecodeOptions { maxResolutionInMP?: number;}
export default function myFormat() { return { mime: "image/heic", hasAlpha: true, encode: async (bitmap: Bitmap, { quality = 90 }: MyEncodeOptions = {}) => { // Don't change bitmap.data: with hasAlpha it's the image's own pixels const bytes = await codec.encode(bitmap.data, bitmap.width, bitmap.height, { quality }); return Buffer.from(bytes); }, decode: async (data: Buffer, { maxResolutionInMP = 100 }: MyDecodeOptions = {}) => { const { width, height, rgba } = await codec.decode(data);
if (width * height > maxResolutionInMP * 1_000_000) { throw new Error(`Image exceeds ${maxResolutionInMP} megapixels`); }
return { data: Buffer.from(rgba), width, height }; }, } satisfies Format<"image/heic", MyEncodeOptions, MyDecodeOptions>;}Jimp finds the right format in two different ways, and both have to know your MIME type:
- Reading.
Jimp.readandJimp.fromBufferdetect the MIME type from the file’s first bytes with thefile-typepackage. It recognizes most common image formats, such as AVIF, HEIC, JPEG XL, ICO and PSD. For a format it can’t recognize, add adetectfunction; see Detecting the format. - Writing.
writelooks up the MIME type from the file extension with themimepackage’s standard types. For a type it doesn’t list, usegetBufferwith the MIME type and write the bytes yourself.
Detecting the format
Some formats have no signature that file-type knows, such as text-based formats like SVG.
Give the format a detect function: it receives the file’s bytes and returns true if they’re in your format.
import type { Format } from "@jimp/types";
const MAGIC = "MYFMT";
export default function myFormat() { return { mime: "image/x-my-format", detect: (data) => data.subarray(0, MAGIC.length).toString("latin1") === MAGIC, encode: (bitmap) => { /* return a Buffer */ }, decode: (data) => { /* return { data, width, height } */ }, } satisfies Format<"image/x-my-format">;}Jimp only calls detect when file-type finds no format that can decode the data, and calls the formats’ detect functions in the order the formats were given.
Keep it cheap: look at the start of the data instead of parsing all of it.
@jimp/wasm-svg uses detect to recognize SVG files.
detect was added in 2.0.
Animated and multi-page formats
A format whose files can hold several images adds decodeFrames and encodeFrames. Formats without them read and write a single frame through decode and encode.
import type { BitmapFrame, DecodedFrames, DecodeFramesOptions, Format } from "@jimp/types";// Your codec: decodeAll returns { frames: [{ bitmap, delay }], loop },// encodeAll returns a Buffer. MyDecodeOptions is as in the template above.import { decodeAll, encodeAll, type MyDecodeOptions } from "./codec.js";
export interface MyFramesOptions { loop?: number;}
export default function myAnimatedFormat() { return { mime: "image/x-my-animation", encode: (bitmap) => encodeAll([{ bitmap }]), decode: (data, options: MyDecodeOptions = {}) => decodeAll(data, options, 1).frames[0]!.bitmap, decodeFrames: ( data, options: MyDecodeOptions = {}, { maxFrames = Infinity }: DecodeFramesOptions = {}, ): DecodedFrames => decodeAll(data, options, maxFrames), encodeFrames: (frames: BitmapFrame[], { loop = 0 }: MyFramesOptions = {}) => encodeAll(frames, loop), } satisfies Format<"image/x-my-animation", undefined, MyDecodeOptions, MyFramesOptions>;}decodeFramesreturns{ frames, loop? }. Each frame is{ bitmap, delay? }, withdelayin milliseconds. Return complete images: if the format stores frames that only update part of the picture, draw them over the previous ones first, as@jimp/js-gifdoes. Stop aftermaxFramesframes, and apply your size limits to all the frames together, as they’re all in memory at once.encodeFramesreceives{ bitmap, delay? }for each frame, already flattened onto the background and converted to sRGB as forencode. Throw if your format can’t store the frames, for example frames of different sizes.- The fourth type parameter of
Formatis the type ofencodeFrames’ options. Jimp uses it to type the options ofencodeFramesandwriteFramesfor your MIME type.
decodeFrames and encodeFrames were added in 2.0. @jimp/js-gif and @jimp/js-tiff implement them.
Format plugins that wrap WebAssembly codecs, such as @jimp/wasm-webp, are good references; see WEBP / WASM and the source in the Jimp repository.
Typing
createJimp infers everything from the plugins and formats you give it, so you don’t write any types for the Jimp class yourself.
- Methods get their parameter types from your functions, minus the first
imageargument. - A method whose return type is the image type parameter (
I, from<I extends JimpClass>(image: I, …)) is typed as chainable: it returns the Jimp image, with all its methods. Any other return type is passed through, soaverageColor()is typed as returningRGBAColor. - Encode and decode options are inferred from the parameter types of
encodeanddecode, soimage.write("photo.jpg", { quality: 80 })is checked against your options type. Usesatisfies Format<Mime>rather than a type annotation, so the inferred types aren’t widened. - The MIME type you give
Formatis used to typegetBufferandwrite:getBuffer("image/heic")only type-checks when the Jimp class includes a format for it.
Use JimpClass from @jimp/types for the image parameter, not the Jimp class from jimp, so the plugin works with any Jimp class, including custom ones.
TypeScript has more on Jimp’s types.
Testing
Create a Jimp class with just your plugin and test it like any other code. This example uses Vitest:
import { describe, expect, test } from "vitest";import { createJimp } from "@jimp/core";
import { methods } from "./index.js";
const Jimp = createJimp({ plugins: [methods] });
describe("vignette", () => { test("darkens the corners but not the center", () => { const image = new Jimp({ width: 9, height: 9, color: 0xffffffff });
image.vignette({ strength: 1 });
expect(image.getPixelColor(0, 0)).toBe(0x000000ff); expect(image.getPixelColor(4, 4)).toBe(0xffffffff); });
test("rejects a strength above 1", () => { const image = new Jimp({ width: 2, height: 2 });
expect(() => image.vignette({ strength: 2 })).toThrow( "Too big: expected number to be <=1", ); });});
describe("averageColor", () => { test("averages every pixel", () => { const image = new Jimp({ width: 2, height: 1, color: 0xff0000ff });
image.setPixelColor(0x0000ffff, 1, 0);
expect(image.averageColor()).toEqual({ r: 128, g: 0, b: 128, a: 255 }); });});Small images built with new Jimp() and checked with getPixelColor keep tests fast and readable.
For bigger effects, compare against a snapshot: Jimp’s own tests use expect(image).toMatchSnapshot() on small bitmaps, and diff can measure how far two images are apart.
To test a format plugin, round-trip an image: encode it, decode the result and compare the pixels.
Publishing
Directoryjimp-plugin-vignette/
Directorysrc/
- index.ts
- index.test.ts
- package.json
- tsconfig.json
- README.md
Publish the plugin as an ES module with its type declarations:
{ "name": "jimp-plugin-vignette", "version": "1.0.0", "type": "module", "exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" } }, "files": ["dist"], "keywords": ["jimp", "jimp-plugin", "image"], "scripts": { "build": "tsc", "test": "vitest" }, "dependencies": { "@jimp/types": "^2.0.0", "zod": "^4.0.0" }, "devDependencies": { "@jimp/core": "^2.0.0", "jimp": "^2.0.0", "typescript": "^5.5.0", "vitest": "^2.0.0" }}- Export
methods(for a method plugin) or a default factory function (for a format plugin), as Jimp’s own packages do. Users can then add it the same way as any built-in plugin. - Don’t depend on
jimpat runtime. A plugin only needs@jimp/types, plus@jimp/core,@jimp/utilsor other plugins if it imports from them. Users bring their own Jimp. - Show the
createJimpsetup in your README, as in step 5 above, since users have to build a custom Jimp to use your plugin.
See also
- Custom Jimp to combine plugins and formats
- Colors and pixels for the bitmap layout
- Drawing for the exported rasterizer, to draw shapes and text outlines
- TypeScript for Jimp’s types
- WEBP / WASM for the WASM format plugins