Jimp
The "JavaScript Image Manipulation Program" :-)
An image processing library for Node written entirely in JavaScript, with zero native dependencies.
Installation: npm install --save jimp
Example usage (Promise will never resolve if callback is passed):
var Jimp = ; // open a file called "lenna.png"Jimp;
Using promises:
Jimp ;
Module Build
If you're using a web bundles (webpack, rollup, parcel) you can benefit from using the module
build of jimp. Using the module build will allow your bundler to understand your code better and exclude things you aren't using.
;
WebPack
If you're using webpack you can set process.browser
to true and your build of jimp will exclude certain parts, making it load faster.
plugins: 'process.browser': 'true' ...
Basic usage
The static Jimp.read
method takes the path to a PNG, JPEG or BMP file and returns a Promise:
Jimp ;
The method can also read a PNG, JPEG or BMP buffer or from a URL:
Jimp ; Jimp ;
Basic methods
Once the promise is fulfilled, the following methods can be called on the image:
/* Resize */image; // scale the image to the given width and height, some parts of the image may be letter boxedimage; // scale the image to the given width and height, some parts of the image may be clippedimage; // resize the image. Jimp.AUTO can be passed as one of the values.image; // scale the image by the factor fimage; // scale the image to the largest size that fits inside the given width and height // An optional resize mode can be passed with all resize methods. /* Crop */image; // automatically crop same-color borders from image (if any), frames must be a Booleanimage; // crop to the given region /* Composing */image; // blit the image with another Jimp image at x, y, optionally cropped.image; // composites another Jimp image over this image at x, yimage; // masks the image with another Jimp image at x, y using average pixel valueimage; // applies a convolution kernel matrix to the image or a region /* Flip and rotate */image; // flip the image horizontally or verticallyimage; // an alias for flipimage; // rotate the image clockwise by a number of degrees. Optionally, a resize mode can be passed. If `false` is passed as the second parameter, the image width and height will not be resized.image; // JPEG images with EXIF orientation data will be automatically re-orientated as appropriate. /* Colour */image; // adjust the brighness by a value -1 to +1image; // adjust the contrast by a value -1 to +1image; // ordered dithering of the image and reduce color space to 16-bits (RGB565)image; // remove colour from the imageimage; // invert the image coloursimage; // normalize the channels in an image /* Alpha channel */image; // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the imageimage; // multiply the alpha channel by each pixel by the factor f, 0 - 1image; // set the alpha channel on every pixel to fully opaqueimagebackground hex ; // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and /* Blurs */image; // Gaussian blur the image by r pixels (VERY slow)image; // fast blur the image by r pixels /* Effects */image; // apply a posterization effect with n levelimage; // apply a sepia wash to the imageimage; // apply a pixelation effect to the image or a region /* 3D */image; // displaces the image pixels based on the provided displacement map. Useful for making stereoscopic 3D images.
Some of these methods are irreversible, so it can be useful to perform them on a clone of the original image:
image; // returns a clone of the image
(Contributions of more methods are welcome!)
Resize modes
The default resizing algorithm uses a bilinear method as follows:
image; // resize the image to 250 x 250image; // resize the height to 250 and scale the width accordinglyimage; // resize the width to 250 and scale the height accordingly
Optionally, the following constants can be passed to choose a particular resizing algorithm:
JimpRESIZE_NEAREST_NEIGHBOR;JimpRESIZE_BILINEAR;JimpRESIZE_BICUBIC;JimpRESIZE_HERMITE;JimpRESIZE_BEZIER;
For example:
image;
Align modes
The following constants can be passed to the image.cover
, image.contain
and image.print
methods:
JimpHORIZONTAL_ALIGN_LEFT;JimpHORIZONTAL_ALIGN_CENTER;JimpHORIZONTAL_ALIGN_RIGHT; JimpVERTICAL_ALIGN_TOP;JimpVERTICAL_ALIGN_MIDDLE;JimpVERTICAL_ALIGN_BOTTOM;
For example:
image;
Default align modes for image.cover
and image.contain
are:
JimpHORIZONTAL_ALIGN_CENTER | JimpVERTICAL_ALIGN_MIDDLE;
Default align modes for image.print
are:
alignmentX: JimpHORIZONTAL_ALIGN_LEFT alignmentY: JimpVERTICAL_ALIGN_TOP
Writing text
Jimp supports basic typography using BMFont format (.fnt) even ones in different languages! Just find a bitmap font that is suitable bitmap fonts:
Jimp;
Alignment modes are supported by replacing the str
argument with an object containing text
, alignmentX
and alignmentY
. alignmentX
defaults to Jimp.HORIZONTAL_ALIGN_LEFT
and alignmentY
defaults to Jimp.VERTICAL_ALIGN_TOP
.
Jimp;
Jimp.loadFont( path, cb ); // using a callback pattern
BMFont fonts are raster based and fixed in size and colour. Jimp comes with a set of fonts that can be used on images:
JimpFONT_SANS_8_BLACK; // Open Sans, 8px, blackJimpFONT_SANS_10_BLACK; // Open Sans, 10px, blackJimpFONT_SANS_12_BLACK; // Open Sans, 12px, blackJimpFONT_SANS_14_BLACK; // Open Sans, 14px, blackJimpFONT_SANS_16_BLACK; // Open Sans, 16px, blackJimpFONT_SANS_32_BLACK; // Open Sans, 32px, blackJimpFONT_SANS_64_BLACK; // Open Sans, 64px, blackJimpFONT_SANS_128_BLACK; // Open Sans, 128px, black JimpFONT_SANS_8_WHITE; // Open Sans, 8px, whiteJimpFONT_SANS_16_WHITE; // Open Sans, 16px, whiteJimpFONT_SANS_32_WHITE; // Open Sans, 32px, whiteJimpFONT_SANS_64_WHITE; // Open Sans, 64px, whiteJimpFONT_SANS_128_WHITE; // Open Sans, 128px, white
These can be used as follows:
Jimp;
Online tools are also available to convert TTF fonts to BMFont format (e.g. Littera).
Writing to files and buffers
Writing to files
The image can be written to disk in PNG, JPEG or BMP format (determined by the file extension) using:
image; // Node-style callback will be fired when write is successfulimage; // Returns Promise
The original extension for an image (or "png") can accessed as using image.getExtension()
. The following will save an image using its original format:
var file = 'new_name.' + image;image;
Writing to Buffers
A PNG, JPEG or BMP binary Buffer of an image (e.g. for storage in a database) can be generated using:
image; // Node-style callback will be fired with resultimage; // Returns Promise
For convenience, supported MIME types are available as static properties:
JimpMIME_PNG; // "image/png"JimpMIME_JPEG; // "image/jpeg"JimpMIME_BMP; // "image/bmp"
If Jimp.AUTO
is passed as the MIME type then the original MIME type for the image (or "image/png") will be used. Alternatively, image.getMIME()
will return the original MIME type of the image (or "image/png").
Data URI
A Base64 data URI can be generated in the same way as a Buffer, using:
image; // Node-style callback will be fired with resultimage; // Returns Promise
PNG and JPEG quality
The quality of JPEGs can be set with:
image; // set the quality of saved JPEG, 0 - 100
The format of PNGs can be set with:
image; // set whether PNGs are saved as RGBA (true, default) or RGB (false)image; // set the filter type for the saved PNGimage; // set the deflate level for the saved PNGJimp; // set the deflate for the saved PNG (0-3)
For convenience, supported filter types are available as static properties:
JimpPNG_FILTER_AUTO; // -1JimpPNG_FILTER_NONE; // 0JimpPNG_FILTER_SUB; // 1JimpPNG_FILTER_UP; // 2JimpPNG_FILTER_AVERAGE; // 3JimpPNG_FILTER_PAETH; // 4
Advanced usage
Colour manipulation
Jimp supports advanced colour manipulation using a single method as follows:
imagecolor apply: 'hue' params: -90 apply: 'lighten' params: 50 apply: 'xor' params: '#06D' ;
The method supports the following modifiers:
Modifier | Description |
---|---|
lighten {amount} | Lighten the color a given amount, from 0 to 100. Providing 100 will always return white (works through TinyColor) |
brighten {amount} | Brighten the color a given amount, from 0 to 100 (works through TinyColor) |
darken {amount} | Darken the color a given amount, from 0 to 100. Providing 100 will always return black (works through TinyColor) |
desaturate {amount} | Desaturate the color a given amount, from 0 to 100. Providing 100 will is the same as calling greyscale (works through TinyColor) |
saturate {amount} | Saturate the color a given amount, from 0 to 100 (works through TinyColor) |
greyscale {amount} | Completely desaturates a color into greyscale (works through TinyColor) |
spin {degree} | Spin the hue a given amount, from -360 to 360. Calling with 0, 360, or -360 will do nothing - since it sets the hue back to what it was before. (works through TinyColor) |
hue {degree} | Alias for spin |
mix {color, amount} | Mixes colors by their RGB component values. Amount is opacity of overlaying color |
tint {amount} | Same as applying mix with white color |
shade {amount} | Same as applying mix with black color |
xor {color} | Treats the two colors as bitfields and applies an XOR operation to the red, green, and blue components |
red {amount} | Modify Red component by a given amount |
green {amount} | Modify Green component by a given amount |
blue {amount} | Modify Blue component by a given amount |
Convolution matrix
Sum neighbor pixels weighted by the kernel matrix. You can find a nice explanation with examples at GIMP's Convolution Matrix plugin
Implement emboss effect:
image;
Low-level manipulation
Jimp enables low-level manipulation of images in memory through the bitmap property of each Jimp object:
imagebitmapdata; // a Buffer of the raw bitmap dataimagebitmapwidth; // the width of the imageimagebitmapheight; // the height of the image
This data can be manipulated directly, but remember: garbage in, garbage out.
A helper method is available to scan a region of the bitmap:
image; // scan a given region of the bitmap and call the function f on every pixel
Example usage:
image;
If you need to do something with the image at the end of the scan:
image;
A helper to locate a particular pixel within the raw bitmap buffer:
image; // returns the index within image.bitmap.data
One of the following may be optionally passed as a third parameter to indicate a strategy for x, y positions that are outside of boundaries of the image:
JimpEDGE_EXTEND = 1;JimpEDGE_WRAP = 2;JimpEDGE_CROP = 3;
Alternatively, you can manipulate individual pixels using the following these functions:
image; // returns the colour of that pixel e.g. 0xFFFFFFFFimage; // sets the colour of that pixel
Two static helper functions exist to convert RGBA values into single integer (hex) values:
Jimp; // e.g. converts 255, 255, 255, 255 to 0xFFFFFFFFJimp; // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255}
Creating new images
If you want to begin with an empty Jimp image, you can call the Jimp constructor passing the width and height of the image to create and a Node-style callback:
256 256 { // this image is 256 x 256, every pixel is set to 0x00000000};
You can optionally set the pixel colour as follows:
256 256 0xff0000ff { // this image is 256 x 256, every pixel is set to 0xFF0000FF};
Comparing images
To generate a perceptual hash of a Jimp image, based on the pHash algorithm, use:
imagehash; // aHgG4GgoFjA
By default the hash is returned as base 64. The hash can be returned at another base by passing a number from 2 to 64 to the method:
imagehash2; // 1010101011010000101010000100101010010000011001001001010011100100
There are 18,446,744,073,709,551,615 unique hashes. The hamming distance between the binary representation of these hashes can be used to find similar-looking images.
To calculate the hamming distance between two Jimp images based on their perceptual hash use:
Jimp; // returns a number 0-1, where 0 means the two images are perceived to be identical
Jimp also allows the diffing of two Jimp images using PixelMatch as follows:
var diff = Jimp; // threshold ranges 0-1 (default: 0.1)diffimage; // a Jimp image showing differencesdiffpercent; // the proportion of different pixels (0-1), where 0 means the images are pixel identical
Using a mix of hamming distance and pixel diffing to compare images, the following code has a 99% success rate of detecting the same image from a random sample (with 1% false positives). The test this figure is drawn from attempts to match each image from a sample of 120 PNGs against 120 corresponding JPEGs saved at a quality setting of 60.
var distance = Jimp; // perceived distancevar diff = Jimp; // pixel difference if distance < 015 || diffpercent < 015 // images match else // not a match
Chaining or callbacks
Most instance methods can be chained together, for example as follows:
Jimp;
Alternatively, methods can be passed Node-style callbacks:
Jimp;
The Node-style callback pattern allows Jimp to be used with frameworks that expect or build on the Node-style callback pattern.
Contributing
Basically clone, change, test, push and pull request.
Please read the CONTRIBUTING documentation.
Testing
The test framework runs in Node.js and browser environments. Just run npm test
to test in Node and browser environments.
More information at "How to Contribute" doc's "Testing" topic.
License
Jimp is licensed under the MIT license. Open Sans is licensed under the Apache license.