Migrate to v2
Every breaking change from Jimp 1.x to 2.0, and how to update your code.
Jimp 2.0 keeps the v1 API. There are no renamed methods and no new import style, so most code runs unchanged. The breaking changes are bug fixes: invalid input that used to give a wrong image now throws, and several methods now compute the result they always claimed to. If you’re coming from v0, read Migrate to v1 first.
To upgrade, install the new major version:
npm install jimp@2Then work through this page. Start with the quick checklist; the sections below it explain each change.
Quick checklist
- Run on Node.js 22 or later. If you use TypeScript, use TypeScript 5.7 or later, or set
skipLibCheck: true. - Look for code that relied on bad input being accepted: invalid CSS colors,
NaNcoordinates, crop rectangles outside the image, conflictingalignflags, ragged convolution kernels, hashes of different lengths, and vector font options with a bitmap font. These now throw. See Errors that now throw. - If you store
pHashorhashvalues, recompute them. Hashes from 1.x can’t be compared with hashes from 2.0. - If you compare output against saved images (snapshot tests, golden files), expect changes in
greyscale,posterize,contrast,normalize,threshold,sepia,mask,convoluteandcolor(); inresize,blur,gaussian,blit,compositeandshadowwith transparency; inrotate,cover,contain,autocrop,displaceandcircle; inprint; and in PNG, GIF, BMP and AVIF files. See Behavior changes. - Remove encode and decode options that no longer exist. TypeScript reports them; see Removed options.
Requirements
Node.js 22 or later
Jimp 2.0 requires Node.js 22 or later. Node.js 18 and 20 are end-of-life and are no longer supported. Every package’s engines field says >=22.
The browser build is unchanged.
TypeScript 5.7 or later
Jimp’s type declarations use generic typed arrays, such as Buffer<ArrayBufferLike> and Uint8Array<ArrayBufferLike>, which need TypeScript 5.7 or later.
With an older TypeScript and skipLibCheck: false, the declarations fail to compile with TS2315: Type 'Buffer' is not generic.
Upgrade TypeScript, or set skipLibCheck: true (the tsc --init default) in your tsconfig.json.
Errors that now throw
In 1.x these inputs were accepted and gave a wrong or empty result, or failed later with an unrelated error. In 2.0 they throw, so mistakes show up where they happen.
- Invalid CSS color strings in
new Jimp({ color })andcssColorToHexthrowInvalid color "notacolor". They used to become opaque black. Fix the color. Options that are new in 2.0 and take CSS colors, such asborder’s andboxShadow’scolor, throw the same error. NaNcoordinates insetPixelColor,getPixelColorandgetPixelIndexthrowhex, x and y must be numbersorx and y must be numbers. They used to read or write pixel (0, 0). Check your coordinate math.- An invalid
alignincoverorcontain, with two flags on one axis, unknown bits or a non-integer, throwsalign must combine at most one HorizontalAlign and one VerticalAlign flag. Pass at most oneHorizontalAlignand oneVerticalAlignflag. - A
croprectangle entirely outside the image, or aworhof 0, throwsThe crop region (x: 10, y: 10, w: 2, h: 2) doesn't overlap the 4x3 image, so the result would be empty. Check the rectangle before cropping. - An unknown blend mode in
compositethrowsUnknown blend mode "nope", expected one of: srcOver, dstOver, multiply, …instead of aTypeError. Use aBlendModevalue. quantizewithcolorsbelow 1, or below 2 withpaletteQuantization: "rgbquant", throwscolors must be at least 1orcolors must be at least 2 for rgbquant.compareHasheswith hashes that aren’t base 64 throws"<hash>" isn't a base 64 hash. Pass the base the hashes were made with to compareHashes, …. Pass the base:compareHashes(a.hash(16), b.hash(16), 16).- Hashes of different lengths in
compareHashesanddistanceFromHashthrowCan't compare hashes of different lengths (64 and 11). …. They used to return a meaningless distance. Compare hashes made with the samesize,smallerSizeand base. - Bitmap data of the wrong length in
Jimp.fromBitmapornew Jimp({ data, width, height })throwsbitmap data is 70 bytes, but a 50x50 RGBA image needs exactly 10000 (width * height * 4). It used to fail later, on the first pixel read. - A ragged kernel, with rows of different lengths, in
convoluteorconvolutionthrowskernel rows must all have the same length. It used to be accepted and gave a wrong image. An empty kernel,[], inconvolutethrowskernel must be a matrix; it used to make the image transparent black. Give every row the same number of values. - Vector font options with a bitmap font.
printwithsize,color,stroke,strokeWidth,lineHeightorletterSpacingand a font fromloadFontthrows, naming the options you passed:print: size, color can only be used with fonts loaded with loadTTF. Bitmap fonts from loadFont are drawn at the size and in the color they were made with.1.x dropped unknown keys without an error. Remove the options, or load a TrueType, OpenType or WOFF font withloadTTF. - GIF, TIFF and BMP files over 100 megapixels throw, for example
GIF dimensions 20000x20000 exceed the maximum resolution of 100 megapixels. JPEG already had this limit. RaisemaxResolutionInMPfor the format; see Reading Large Images. - BMFont pages outside the font’s directory throw
Font page is outside of the font directory: ../secret.png. Keep a font’s page images next to its.fntfile. - Unknown options in the WASM encoders (
@jimp/wasm-avif,@jimp/wasm-jpeg,@jimp/wasm-pngand@jimp/wasm-webp) throw aZodErrornaming the key. They used to be dropped silently. Remove the option.
Some error messages also changed:
- In Node.js,
Jimp.readwith a missing file throws Node’s own error,ENOENT: no such file or directory, open './typo.png', instead ofCould not load Buffer from URL: ./typo.png. SeeJimp.readreads paths as files. writewith a path that has no extension throwsCannot write "<path>": the path has no recognisable file extension to determine the image formatinstead ofUnsupported MIME type: null.- In Node.js,
loadFontwith a path that doesn’t exist throwsloadFont: font file not found: "fonts/typo.fnt". …instead ofFailed to parse URL from fonts/typo.fnt. A page image missing from next to the.fntfile throwsloadFont: font page not found: "<path>". …. loadFontwith a URL that returns an error status throwsloadFont: couldn't load "<url>": HTTP 404 Not Found. It used to try to parse the error page as a font.- An empty kernel row in
convoluteorconvolutionthrowskernel rows must not be emptyinstead of zod’s genericToo small: expected array to have >=1 items.
Behavior changes
These don’t throw, but the output is different. Most are fixes for results that were wrong in 1.x. Each item says what changed and, where there’s something to do, what to do.
Regions and pixels
-
Out-of-bounds regions are clamped to the image.
cropreturns only the part of the rectangle inside the image and never grows it.blit,pixelate,convolute,scanandscanIteratorskip the part of their region outside the image. In 1.x they wrapped onto the next row, read outside the bitmap, or threw aRangeError.crop.ts const image = new Jimp({ width: 4, height: 3 });image.crop({ x: 3, y: 0, w: 2, h: 2 });// 1.x: 2x2, with a column wrapped from the next row// 2.0: 1x2, the part that's inside the image -
scanIterator(x, y)defaults to the rest of the image. Withoutwandhit used to iterate a full image’s worth of pixels starting at(x, y). -
setPixelColoroutside the image does nothing, like canvas. In 1.x it painted the nearest edge pixel. If you relied on that, clamp the coordinates yourself. Reads are unchanged:getPixelColoroutside the image still returns the nearest edge pixel. -
getPixelIndex(x, y, Edge.WRAP)wraps any distance. It used to return-1for coordinates more than one image width away on the negative side.
Color math
greyscalerounds instead of truncating, so many pixels come out one level brighter and gray pixels keep their value.0x050505ffused to become0x040404ff.color([{ apply: "greyscale" }])matchesgreyscale(). It now uses the same Rec. 709 luminance. It used to use HSL lightness, so red became128instead of54.posterizerounds each channel to the nearest ofnevenly spaced levels. It used to round down, soposterize(2)on[200, 127, 64]gave black; it now gives[255, 0, 0].nis rounded and clamped to 2–256.contrastscales around 127.5 instead of 127 and rounds halves away from the middle.contrast(-1)gives 128 (it was 127); other values change by at most one level.normalizeleaves a channel alone when every pixel has the same value. It used to turn it black.thresholdwithautoGreyscale: falsecompares and replaces red, green and blue separately, so colors are kept. It used to compute gray from the red channel alone. With the defaultautoGreyscale: true, output changes slightly because of thegreyscalerounding.color()’ssaturate,desaturate,lightenanddarkenscale and blend instead of adding a fixed amount.darken30 on pure red now gives(179, 0, 0)instead of(102, 0, 0), andlightenno longer blows highlights out to white.sepiacomputes each channel from the original pixel. Pure red now becomes(100, 88, 69); 1.x gave(100, 34, 45).maskuses luminance for color masks instead of the average of R, G and B, multiplies in the mask’s own alpha (transparent mask pixels now hide the image), and rounds. Opaque gray masks on opaque images give the same result as before.convolutereads its kernel askernel[row][col], likeconvolution. It used to apply every kernel transposed. Symmetric kernels (blur, sharpen, Laplacian) are unaffected; for kernels such as Sobel-x, 1.x gave Sobel-y output. If you transposed a kernel to compensate, undo that.
Transparency and compositing
-
resizeuses premultiplied alpha in the default resizer and inBILINEAR,BICUBIC,HERMITEandBEZIER, so transparent pixels no longer darken their neighbors. This doesn’t change opaque images. If your alpha channel holds data rather than opacity, passpremultiplyAlpha: false.resize.ts // A white pixel next to a transparent one, enlarged// 1.x: d5d5d5d5 (gray) 2.0: ffffffd5 (white)image.resize({ w: 4 }); -
The default resizer rounds when only the width changes. It used to truncate, so some channel values came out one level lower. This also changes opaque images.
-
BICUBIC,HERMITEandBEZIERno longer shift the image toward the top left or drop the last row and column. -
blurandgaussianweight colors by alpha, so edges next to transparent pixels keep their color instead of fading to black. Opaque images are unchanged by this. -
gaussianis a true Gaussian blur. It used to read pixels it had already blurred, so its output changes for every image. It now also accepts radii between 0 and 1. -
blurrounds its radius and clamps it to 1–256.blur(2.5)and radii above 256 used to make the image transparent black. -
blituses source-over compositing, the same formula ascomposite. Blitting a semi-transparent pixel onto a transparent image used to darken it: white at alpha0x80became80808080, nowffffff80. Printed text on transparent images loses its dark fringe for the same reason. -
compositerounds its results instead of truncating them, so an opaque source always gives alpha 255. It clampsopacitySourceandopacityDestto 0–1: a negative value used to mean 1 and now means 0. It also accepts images from any Jimp class, such as a custom Jimp. -
shadowdraws a dark shadow under the image. 1.x drew a blurred copy of the image over it. The shadow is centered on the image beforexandyare applied, so the default output changes too.
Shape
rotaterotates about the center. Angles that aren’t multiples of 90° used to shift the image one pixel up and left. Withmode: truethe canvas is the rotated bounding box rounded up, so it’s often 1–2 pixels smaller: an 8×8 image at 45° gives 12×12 instead of 14×14. Multiples of 90° are unchanged, except 90° and 270° withmode: falseon a non-square image: those are now centered, where they used to be one pixel off.rotate({ deg, mode: ResizeStrategy.X })interpolates with that strategy. In 1.x anyResizeStrategygave the same nearest-neighbor result astrue. The canvas size is unchanged.coverandcontaincenter an axis thatalignleaves out.align: VerticalAlign.TOPused to align to the left as well; it now centers horizontally. PassHorizontalAlign.LEFT | VerticalAlign.TOPfor the 1.x result.autocropcrops in more cases:ignoreSidesworks with the defaultcropOnlyFrames: true, a largeleaveBorderno longer cancels the crop, and fully transparent pixels all count as the same color.displacemoves alpha with the pixel and stretches a map of a different size to the image.circle({ radius: 0 })makes the image fully transparent. It used to mean the default radius. Leaveradiusout to get the default.
Text
-
Alignment works without
maxWidthandmaxHeight.printlays text out in a box fromx,yto the right and bottom edges of the image.alignmentX: HorizontalAlign.CENTERwithoutmaxWidthused to throw aZodError, andalignmentYwithoutmaxHeightwas ignored. Text still only wraps at an explicitmaxWidth.print.ts // 1.x: threw. 2.0: centers "Hi" in the image, to the right of ximage.print({font,x: 0,y: 0,text: { text: "Hi", alignmentX: HorizontalAlign.CENTER },}); -
Blank lines are kept. Every line break starts a new line, so
"a\n\nb"prints three lines. Line breaks used to collapse into one.measureTextHeight, vertical alignment and theypassed to the callback count the empty lines. -
measureTexttreats line breaks as line breaks and returns the width of the widest line. It used to skip them and measure the text as one line.measureTextHeight’smaxWidthis now optional. -
Characters the font has no glyph for are measured as the
?thatprintdraws.measureTextused to count them as 0 wide, so text with missing characters could overflowmaxWidthand right- or center-aligned lines were placed wrongly. Text with such characters now wraps and aligns differently. -
Wrapping keeps whole words. A word is only split when it’s wider than
maxWidthon its own, and the end of a long word is no longer dropped. Spaces at a wrap point are removed instead of making a line of spaces. -
Characters outside the Basic Multilingual Plane, such as emoji and rare CJK characters, print when the font has them. They used to print as
??. -
maxHeightstill doesn’t clip text. It’s only used for vertical alignment.
Hashes
-
pHashandhashgive different values for every image. The average now leaves out the DC term, as the algorithm intends. In 1.x the DC term dominated on bright, low-contrast images, so many different images got nearly the same hash, with almost every bit 0. Transparent pixels are also composited onto gray before hashing, so hidden colors under alpha 0 don’t change the hash.Hashes from 1.x and 2.0 can’t be mixed: a
compareHashesordistanceFromHashdistance between a stored 1.x hash and a 2.0 hash means nothing. Re-hash every stored image with 2.0.distance(a, b)on two images is fine, since it hashes both with the same version. -
compareHashesdecodeshash()output to binary before comparing, socompareHashes(a.hash(), b.hash())equalsdistance(a, b). It used to compare base 64 characters, which gave much larger distances. Passbasefor hashes in other bases.
Reading and writing
Jimp.read reads paths as files
In Node.js, Jimp.read only fetches http:, https:, data: and blob: URLs. Any other string is read from disk.
In 1.x a path that didn’t exist was then fetched as a URL. Browsers still fetch every string.
try { await Jimp.read("./typo.png");} catch (error) { // 1.x: Could not load Buffer from URL: ./typo.png // 2.0: ENOENT: no such file or directory, open './typo.png'}Jimp.read and Jimp.fromBuffer also accept a Uint8Array, any ArrayBuffer view and a Blob.
Other changes
- PNG output uses the smallest lossless color type. Without a
colorTypeoption, opaque images are written as RGB and gray images as grayscale, instead of always RGBA. The pixels are identical, and files are smaller. PasscolorType: PNGColorType.COLOR_ALPHAif something downstream needs RGBA.inputHasAlphais deprecated; usecolorType. Jimp.readpasses decode options for files and buffers. In 1.x, the per-format options passed toJimp.read, such as{ "image/jpeg": { maxMemoryUsageInMB: 1024 } }, were only used when reading a URL. They’re now used for file paths and buffers too, so options you passed before may now take effect.Jimp.fromBufferalready used them.clonecopiesmime,background, the EXIF data and the ICC profile. The clone used to have nomime, a transparent background and no EXIF data.- ICC color profiles are kept. JPEG, PNG and WebP files keep their embedded profile when you write them, so Display P3 photos no longer look duller after a round trip. For images with a profile, CSS colors are converted to the image’s color space, and GIF, BMP, TIFF and AVIF output is converted to sRGB. Images without a profile are unchanged. Set
image.iccProfile = undefinedfor the 1.x behavior. See Color Spaces. - GIF encoding keeps images with up to 256 colors exact, and quantizes larger ones in constant memory, so large GIFs no longer run out of memory. The output for images with more than 256 colors differs from 1.x.
- BMPs with an alpha mask keep their transparency. 16- and 32-bit BMPs that store alpha, as GIMP and ImageMagick write them, used to load fully opaque. 32-bit BMPs without an alpha mask still load opaque.
- AVIF files written with
@jimp/wasm-avifdiffer from 1.x. The plugin now uses libavif 1.0, so the encoded bytes and file sizes change. The options, includingcqLevelandcqAlphaLevel, keep their names and meaning. See AVIF. fromBitmapand the constructor copyUint8ClampedArrayandUint8Arraydata, such as a canvas’sImageData. In 1.xfromBitmapshared memory with the array you passed, so editing the image could change it.@jimp/*packages publish onlydist/. Imports from a package’ssrc/folder no longer resolve. Import from the package name.
Removed options
These options were accepted but had no effect, or broke the output. They’re removed from the types; TypeScript points out every use.
| Package | Removed | What to do |
|---|---|---|
@jimp/js-bmp |
colors, importantColors and the old palette of { red, green, blue, quad } objects; the BmpColor type |
1.x always wrote a 24-bit BMP. To write a palette BMP, use the new bitPP: 1 | 4 | 8 with an optional palette of CSS colors or numbers; see BMP. |
@jimp/js-png (encode) |
width, height, fill, checkCRC, skipRescale, deflateFactory, deflateChunkSize |
Remove them. Width, height and fill come from the image. |
@jimp/js-png (decode) |
skipRescale |
Remove it. It made 16-bit PNGs throw; PNGs are always decoded to 8 bits per channel. checkCRC is still accepted. |
@jimp/js-jpeg (decode) |
useTArray |
Remove it. Its only allowed value was the default. |
@jimp/js-gif |
the unused JPEGOptions type |
Remove the import. |
@jimp/wasm-avif, @jimp/wasm-jpeg, @jimp/wasm-png, @jimp/wasm-webp |
colorSpace |
Remove it. Use the image’s color space and the icc option. |
@jimp/wasm-webp |
threadLevel, useDeltaPalette, showCompressed |
Remove them. They didn’t change the file. |
// 1.x: accepted, but the file was always 24-bitawait image.write("out.bmp", { palette: [{ red: 0, green: 0, blue: 0, quad: 0 }], colors: 2 });
// 2.0await image.write("out.bmp", { bitPP: 1, palette: ["black", "white"] });Types
-
write()andgetBuffer()options are typed by extension. The format comes from the path’s last extension, ignoring case and including.jpg,.jpeand.tif, so"./out/a.v2.JPG"takes JPEG options. GIF and TIFF take no options.write.ts await image.write("photo.JPG", { deflateLevel: 5 });// 1.x: compiled. 2.0: error, deflateLevel isn't a JPEG option -
write()accepts a plainstringpath, such as one frompath.join, and takes the options of any installed format. Keys that no format takes are an error. -
Jimp image types are interchangeable. Images from
new Jimp(),Jimp.read()and chained methods can be assigned to each other and toJimpInstance, andJimp.fromBitmap()is no longer typedany. You can remove casts you added to work around this. -
EdgeandColorActionNameare runtime values.import { Edge } from "jimp"used to be type-only, soEdge.WRAPwasundefinedat runtime.
New in 2.0
2.0 also adds methods, options and formats. Each page has the details.
Color
- Color spaces: Display P3 and ICC profiles are read, kept and converted, with
toColorSpaceandnew Jimp({ colorSpace: "display-p3" }).icc: falsewrites a JPEG, PNG or WebP converted to sRGB without a profile, andcssColorToHextakes a color space and parsescolor(display-p3 …)colors. exposure(in stops, in linear light) andvibrance.sepia(amount)and amultiplycoloraction.mixandxoraccept CSS colors.dithertypes"floyd-steinberg","atkinson","bayer4"and"bayer8", with a palette.dither()with no options is unchanged.threshold({ max: "otsu" })andotsuThresholdpick the level automatically.
Drawing
- Vector drawing, from the new default plugin
@jimp/plugin-draw:drawLine,drawRect,drawEllipse,drawPolygon,drawPath(SVG path data) andfloodFill. Shapes are antialiased and take colors or linear and radial gradients. See Drawing. - The rasterizer behind them is exported from
@jimp/plugin-drawfor plugins that draw their own shapes.
Effects
sharpen.divisorandbiasforconvolutionandconvolute,preserveAlphaforconvolute, and even-sized and non-square kernels.roundCorners,borderandboxShadow, modeled on the CSS properties.displacealong both axes withoffset: { x, y }.erode,dilate,openandclosemorphology operations, from the new default plugin@jimp/plugin-morphology:image.erode({ radius: 2, shape: "disk" }).difftakes pixelmatch’s options, includingdiffMaskfor a transparent diff and custom diff colors.
Shape
skewandaffinetransforms.ResizeStrategy.LANCZOS,LANCZOS2andMITCHELLforresizeand every method that takes a resize mode.premultiplyAlphaforresize,scale,scaleToFit,coverandcontain.- Fractional
align: { x, y }forcoverandcontain, like CSSobject-position. autocropRectreturns the rectangleautocropwould crop to.
Text
- TrueType, OpenType and WOFF fonts:
loadTTF, fromjimp/load-ttf, loads them.printdraws them at anysize, withcolor(a color or a gradient),stroke,strokeWidth,lineHeightandletterSpacing.measureTextandmeasureTextHeightmeasure them, with{ size, lineHeight?, letterSpacing? }as their last argument. See Text and Fonts.
Reading and writing
- ICO is a default format: read
.icoand.cur, write.ico.readIcoEntriesfrom@jimp/js-icolists the images in a file. See ICO. - Animated GIFs and multi-page TIFFs:
Jimp.readFramesandJimp.fromBufferFramesread every frame or page, andJimp.encodeFramesandJimp.writeFrameswrite them. - Format plugins can add a
detectfunction, to recognize formats thatfile-typedoesn’t know, such as SVG, anddecodeFramesandencodeFramesfor multi-frame formats. See Detecting the format and Animated and multi-page formats. - BMP output at 1, 4, 8, 16, 24 or 32 bits per pixel with the
bitPPoption, and palettes for 1, 4 and 8 bits. - New WASM format plugins:
@jimp/wasm-jpeg2000(JPEG 2000),@jimp/wasm-jxl(JPEG XL) and@jimp/wasm-svg(reads SVG). See WEBP / WASM. - WASM plugins accept precompiled modules, for Cloudflare Workers.
exifRotate: falsekeeps a JPEG’s stored orientation when reading, andexif: truekeeps EXIF data when writing a JPEG. See EXIF.Jimp.fromBitmapand the constructor acceptImageData,Uint8ClampedArrayandUint8Array.maxResolutionInMPdecode option for GIF, TIFF and BMP.sizeandsmallerSizeoptions forpHash,hashanddistance.
Performance
These changes make methods faster. On their own, they don’t change the output.
resizeis faster with the default resizer and withBILINEAR,BICUBIC,HERMITEandBEZIER, often several times faster on large images.cropcopies whole rows instead of one pixel at a time, so cropping part of a large image is many times faster.autocropgets faster too.colorno longer creates color objects for every pixel, so its actions run much faster on large images.printandmeasureTextHeightwrap text in linear time. Wrapping long text used to take time proportional to the square of its length.