TypeScript
Jimp is written in TypeScript. Learn the image and option types, and how to type your own plugins and custom Jimp.
Jimp is written in TypeScript and ships its own type definitions, so there’s nothing extra to install.
Every method is typed from the plugins that provide it, option objects are checked, and the formats you can write are known at compile time.
This page covers the types you’ll use most, how a Jimp class gets its types, and how to type a plugin of your own.
The image type
Jimp.read, Jimp.fromBuffer, new Jimp() and every chainable method all return the same type.
To use it in your own code, such as a function parameter, import JimpInstance:
import { Jimp, type JimpInstance } from "jimp";
export async function makeThumbnail(path: string): Promise<JimpInstance> { const image = await Jimp.read(path); return image.resize({ w: 200 });}JimpInstance is InstanceType<typeof Jimp>: the base class (bitmap, width, getPixelColor, getBuffer…) plus every method from the default plugins.
Chains keep the type, so image.resize({ w: 200 }).greyscale().blur(2) is still a JimpInstance, and a method that doesn’t exist is a compile error.
Option types
The option objects of the built-in methods are exported as types, so you can build them ahead of time:
import { Jimp, type ResizeOptions, type ColorAction } from "jimp";
const small: ResizeOptions = { w: 200 };const warm: ColorAction[] = [ { apply: "hue", params: [-10] }, { apply: "saturate", params: [20] },];
const image = await Jimp.read("photo.jpeg");image.resize(small).color(warm);| Type | For |
|---|---|
ResizeOptions, ScaleOptions, ScaleToFitOptions |
resize, scale, scaleToFit |
CropOptions, AutocropOptions |
crop, autocrop |
ContainOptions, CoverOptions |
contain, cover |
AffineOptions, SkewOptions |
affine, skew |
FlipOptions, CircleOptions, FisheyeOptions, DisplaceOptions |
flip, circle, fisheye, displace |
BorderOptions, RoundCornersOptions, CornerRadius, BoxShadowOptions |
border, roundCorners, boxShadow |
ColorAction, and types for single actions such as HueAction or MixAction |
color |
ThresholdOptions, OtsuThresholdOptions |
threshold, otsuThreshold |
DitherOptions, DitherPalette |
dither |
MorphologyOptions |
erode, dilate, open, close |
PrintFontOptions, VectorFont, VectorTextOptions, VectorTextLayoutOptions |
print with a font from loadTTF, measureText, measureTextHeight. FontSource, what loadTTF accepts, is exported from jimp/load-ttf. |
PHashOptions |
pHash |
DiffOptions, DiffColor |
diff |
ReadOptions |
Jimp.read, Jimp.fromBuffer |
ReadFramesOptions, JimpFrames, JimpFrame, FrameInput, EncodeGifFramesOptions |
Jimp.readFrames, Jimp.encodeFrames, Jimp.writeFrames |
JPEGOptions, EncodeOptions (BMP) |
Writing JPEG and BMP |
JimpConstructorOptions, JimpSimpleConstructorOptions, RawImageData |
new Jimp(), Jimp.fromBitmap |
ColorSpaceName |
image.colorSpace, toColorSpace, the colorSpace option of new Jimp() |
ReadOptions covers the options every format shares, such as exifRotate. The read options of a particular Jimp class, with each format’s decode options added, are CreateReadOptions<...> from @jimp/core; in most code, Parameters<typeof Jimp.read>[1] is simpler.
The full list, with every property, is in the type reference.
Types that aren’t exported
A few option types, such as those of blit, mask, print and quantize, aren’t exported by jimp.
Get them from the method with Parameters:
import type { JimpInstance } from "jimp";
type BlitOptions = Parameters<JimpInstance["blit"]>[0];type PrintOptions = Parameters<JimpInstance["print"]>[0];Pixels and colors
These types describe the image data and the color helpers. See Colors and pixels for how they’re used.
| Type | Shape | Used by |
|---|---|---|
Bitmap |
{ data: Buffer; width: number; height: number } |
image.bitmap |
RGBAColor |
{ r: number; g: number; b: number; a: number } |
intToRGBA, colorDiff |
RGBColor |
{ r: number; g: number; b: number } |
colorDiff, the mix, multiply and xor color actions |
Edge |
an enum: EXTEND (1), WRAP (2), CROP (3) |
getPixelIndex, convolution |
import { intToRGBA, type JimpInstance, type RGBAColor } from "jimp";
function averageColor(image: JimpInstance): RGBAColor { const sum = { r: 0, g: 0, b: 0, a: 0 };
for (const { x, y } of image.scanIterator()) { const color = intToRGBA(image.getPixelColor(x, y)); sum.r += color.r; sum.g += color.g; sum.b += color.b; sum.a += color.a; }
const n = image.width * image.height; return { r: sum.r / n, g: sum.g / n, b: sum.b / n, a: sum.a / n };}Edge is both a type and a value, so import { Edge } from "jimp" gives you Edge.WRAP at run time too. See Constants and enums.
MIME types and format options
The formats a Jimp class supports are part of its type.
getBuffer and getBase64 only accept those MIME types, and the options object is checked against that format’s options:
await image.getBuffer("image/jpeg", { quality: 80 }); // OK
await image.getBuffer("image/webp");// Error: Argument of type '"image/webp"' is not assignable to parameter// of type '"image/bmp" | "image/tiff" | "image/x-ms-bmp" | "image/gif" | ...'.
await image.getBuffer("image/jpeg", { deflateLevel: 9 });// Error: 'deflateLevel' does not exist in type 'JPEGOptions'.write works the format out from the path’s last extension, so image.write("photo.png", { quality: 80 }) is an error too: quality is a JPEG option.
The extension can be in any case and can follow directories and other dots, so "./out/photo.v2.JPG" takes JPEG options.
GIF and TIFF have no encode options, so write and getBuffer accept none for them.
Jimp.encodeFrames and Jimp.writeFrames are typed the same way, with each format’s options for several frames: loop for GIF and nothing for TIFF.
For a path held in a string variable, or an unknown extension, write can’t tell the format. It accepts the options of any supported format and rejects keys that no format has.
How createJimp builds the types
The Jimp class exported by jimp is made by createJimp from @jimp/core:
export const Jimp = createJimp({ formats: defaultFormats, plugins: defaultPlugins,});createJimp infers the class’s type from what you pass it:
- Methods come from
plugins. Each plugin is an object of functions that take the image as their first argument. Every function becomes a method without that first argument:resize(image, options)becomesimage.resize(options). - Chainable or not is decided by the return type. A function that returns the image becomes a method that returns the class instance, so the chain continues. A function that returns anything else, such as
pHash’sstring, returns that type and ends the chain. - MIME types come from
formats. Each format declares itsmimeas a string literal, and the union of them is whatgetBufferaccepts. Each format’s encode and decode option types are attached to its MIME type.
So a Custom Jimp with fewer plugins and formats has a narrower type:
import { createJimp } from "@jimp/core";import png from "@jimp/js-png";import * as resize from "@jimp/plugin-resize";
const SmallJimp = createJimp({ plugins: [resize.methods], formats: [png] });
const image = await SmallJimp.read("photo.png");
image.resize({ w: 100 }); // OKimage.blur(3); // Error: Property 'blur' does not existawait image.getBuffer("image/jpeg"); // Error: only "image/png" is supportedUse InstanceType<typeof SmallJimp> for the instance type of a custom class, the same way JimpInstance is defined.
Typing a plugin
A plugin is an object of functions whose first parameter is the image.
Type that parameter with a generic constrained to JimpClass from @jimp/types, and return it for a chainable method:
npm install @jimp/core @jimp/typesimport type { JimpClass } from "@jimp/types";
export const methods = { /** Swap the red and blue channels. Returns the image, so it chains. */ swapRedBlue<I extends JimpClass>(image: I) { image.scan((x, y, idx) => { const { data } = image.bitmap; const red = data[idx]; data[idx] = data[idx + 2]; data[idx + 2] = red; });
return image; },
/** Count the pixels of one color. Returns a number, so it ends a chain. */ countColor<I extends JimpClass>(image: I, color: number) { let count = 0;
image.scan((x, y) => { if (image.getPixelColor(x, y) === color) count++; });
return count; },};JimpClass describes what every Jimp image has: bitmap, background, getPixelIndex, getPixelColor, setPixelColor and scan.
Using a generic I rather than JimpClass itself keeps the caller’s full image type when the method returns the image.
Add the plugin to a class with createJimp, next to the default plugins:
import { createJimp } from "@jimp/core";import { defaultFormats, defaultPlugins } from "jimp";import * as channels from "./channels.js";
export const Jimp = createJimp({ plugins: [...defaultPlugins, channels.methods], formats: defaultFormats,});
export type JimpInstance = InstanceType<typeof Jimp>;The new methods are typed like the built-in ones:
import { Jimp } from "./jimp.js";
const image = await Jimp.read("photo.png");
const count = image.swapRedBlue().resize({ w: 100 }).countColor(0x0000ffff); // number
image.swapRedBlue(5); // Error: Expected 0 arguments, but got 1.A few things to know when you write plugin methods:
- Return the image to chain. If a method returns nothing, calling it returns
undefinedand the chain breaks. - Returning a new image works too. If a method returns a different object with a
bitmap, Jimp copies that bitmap into the image the method was called on and returns the original image. - Validate options at run time. Types only help TypeScript callers. The built-in plugins validate their options with zod schemas and export the inferred types, for example
export type FlipOptions = z.infer<typeof FlipOptionsSchema>.
For format plugins, and more on how plugins are structured, see Writing Plugins.
See also
- Custom Jimp: pick only the plugins and formats you need.
- Writing Plugins: methods and image formats.
- Constants and enums: the enums used in option types.
- Colors and pixels: working with
Bitmapand colors. - Type reference: every exported type, generated from the source.