Colors and pixels
How Jimp stores pixels, how to read and write them, and the helpers for converting colors.
Every Jimp image is a grid of pixels stored in one flat buffer of bytes, four bytes per pixel.
Built-in methods such as blur or greyscale work on that buffer for you, but when you need an effect Jimp doesn’t have, or want to measure something about an image, you read and write the pixels yourself.
This page covers how the pixels are laid out, the methods for reaching them, and the helpers for converting between color formats.
The bitmap
An image’s pixels live in image.bitmap, a Bitmap object with three properties:
| Property | Type | Description |
|---|---|---|
width |
number |
Width in pixels. Also available as image.width. |
height |
number |
Height in pixels. Also available as image.height. |
data |
Buffer |
The pixels, width * height * 4 bytes long. |
data holds the pixels row by row, starting at the top-left corner.
Each pixel takes four bytes, always in the same order, each from 0 to 255:
| Byte | Channel | Meaning |
|---|---|---|
idx |
red | |
idx + 1 |
green | |
idx + 2 |
blue | |
idx + 3 |
alpha | 0 is fully transparent, 255 opaque. |
Every image is stored this way, whatever format it was read from: a JPEG gets an alpha of 255 everywhere, and a palette-based GIF is expanded to full RGBA.
It’s the same layout as the canvas ImageData, so you can copy between them directly; see Using in Browser.
Finding a pixel
The first byte of the pixel at x, y is at index (y * width + x) * 4:
import { Jimp } from "jimp";
const image = await Jimp.read("photo.png");const { data, width } = image.bitmap;
const x = 10;const y = 20;const idx = (y * width + x) * 4;
const [r, g, b, a] = data.subarray(idx, idx + 4);getPixelIndex does this calculation for you, and decides what happens to coordinates outside the image.
Colors as numbers
Methods that read or take a single color use one number in 0xRRGGBBAA form: two hex digits each for red, green, blue and alpha.
0xff0000ff; // opaque red0x00ff0080; // half-transparent green0xffffffff; // opaque white0x00000000; // transparent blackNote the alpha at the end: 0x0000ff (blue without alpha digits) is 0x000000ff, which is opaque black.
The numbers are unsigned 32-bit integers from 0 to 0xffffffff.
Several helpers convert between this form and others:
| Helper | Converts | Example |
|---|---|---|
intToRGBA |
number to { r, g, b, a } |
0xff8800ff → { r: 255, g: 136, b: 0, a: 255 } |
rgbaToInt |
four channels to number | 255, 136, 0, 255 → 0xff8800ff |
cssColorToHex |
CSS string to number | "rgba(255, 0, 0, 0.5)" → 0xff000080 |
limit255 |
any number to the 0–255 range |
300 → 255 |
colorDiff |
two colors to a difference, 0 to 1 |
black and white → 1 |
All of them are named exports of jimp:
import { intToRGBA, rgbaToInt, cssColorToHex, limit255, colorDiff } from "jimp";Convert an RGBA integer such as 0xff0000ff to { r, g, b, a }.
rgbaToInt()Convert red, green, blue and alpha values to an RGBA integer.
cssColorToHex()Convert a CSS color string to an RGBA integer.
Rendering…colorDiff()Measure how different two colors are, from 0 to 1.
Rendering…limit255()Clamp a number to the 0 to 255 range.
CSS color strings
A few APIs accept a CSS color string as well as a number: the color of new Jimp({ width, height, color }), the color options of border and boxShadow, and the mix, multiply and xor actions of color.
They’re converted with cssColorToHex.
The pixel methods don’t: setPixelColor only takes a number, so convert strings first.
import { Jimp, cssColorToHex } from "jimp";
const image = new Jimp({ width: 100, height: 100, color: "#ffeedd" }); // a string works here
image.setPixelColor(cssColorToHex("tomato"), 10, 10); // but not hereA string that isn’t a color throws, for example Invalid color "nope".
Building numbers yourself
If you assemble a color with bit operators, finish with >>> 0.
JavaScript’s << and | produce signed 32-bit numbers, so any color with red 128 or above comes out negative, and setPixelColor throws a RangeError for negative numbers.
const r = 200, g = 100, b = 50, a = 255;
const wrong = (r << 24) | (g << 16) | (b << 8) | a; // -932957441const right = ((r << 24) | (g << 16) | (b << 8) | a) >>> 0; // 0xc86432ff
// or let the helper do it:const same = rgbaToInt(r, g, b, a); // 0xc86432ffReading and writing single pixels
getPixelColor reads a pixel as a number and setPixelColor writes one.
Note that setPixelColor takes the color first:
import { Jimp, intToRGBA } from "jimp";
const image = await Jimp.read("photo.png");
const color = image.getPixelColor(10, 20);const { r, g, b, a } = intToRGBA(color);
image.setPixelColor(0xff0000ff, 10, 20); // make it redsetPixelColor replaces all four channels, including alpha. It doesn’t blend the new color with the old one; use composite for that.
Try both: click the image to pick a pixel for getPixelColor, or to place a dot drawn with setPixelColor.
const color = image.getPixelColor(180, 151)Docs →Read the color of one pixel and paint a swatch with it in the top-left corner. Click the image to pick the pixel.
import { Jimp } from "jimp"; const image = await Jimp.read("dice.png"); // Click a method above to add it here await image.write("output.png");
Coordinates outside the image
Coordinates are rounded to whole pixels, and coordinates outside the image don’t throw:
getPixelColorreads the nearest edge pixel, sogetPixelColor(-5, 0)returns the color of(0, 0).setPixelColordoes nothing, like drawing outside a canvas, sosetPixelColor(color, 500, 0)on a 100-pixel-wide image leaves the image unchanged. Shapes drawn across the border are clipped.
NaN coordinates throw, so a bad calculation doesn’t silently change pixel (0, 0).
Edge handling
getPixelIndex takes an optional third argument that controls what happens to coordinates outside the image. Its values come from the Edge enum:
| Value | Name | Outside coordinates |
|---|---|---|
1 |
Edge.EXTEND |
Clamp to the nearest edge pixel (default). |
2 |
Edge.WRAP |
Wrap around to the opposite side. |
3 |
Edge.CROP |
Return -1. |
import { Edge } from "jimp";
const idx = image.getPixelIndex(x - 10, y, Edge.CROP);
if (idx !== -1) { // the pixel exists}The same enum is used by the edgeHandling option of convolution.
See Constants and enums.
Looping over pixels
To work on many pixels, use scan or scanIterator.
Both visit every pixel of the image, or of a region, row by row, and give you x, y and the pixel’s index idx.
scan takes a callback:
image.scan((x, y, idx) => { const { data } = image.bitmap; data[idx] = 255 - data[idx]; // invert red data[idx + 1] = 255 - data[idx + 1]; // invert green data[idx + 2] = 255 - data[idx + 2]; // invert blue});
// only a 50 × 50 region at (10, 10)image.scan(10, 10, 50, 50, (x, y, idx) => { image.bitmap.data[idx + 3] = 0;});scanIterator gives you an iterator for for...of, so you can break early:
let hasRed = false;
for (const { idx } of image.scanIterator()) { if (image.bitmap.data[idx] > 200) { hasRed = true; break; }}Choose an effect, turn on a region, and compare the two loops in the code panel:
image.scan((x, y, idx) => {Docs →Run a function for every pixel, or every pixel in a region. Pick what the function does.
import { Jimp } from "jimp"; const image = await Jimp.read("dice.png"); // Click a method above to add it here await image.write("output.png");
Both clamp the region to the image, so a region that reaches past an edge only visits the pixels inside the image.
Performance
From fastest to slowest:
- A plain loop over
image.bitmap.data, four bytes at a time, when you don’t needxandy. scan.scanIterator, which creates an object for every pixel; it takes roughly two to three times as long asscan.getPixelColorandsetPixelColorfor every pixel, which compute an index and convert the color on every call.
const { data } = image.bitmap;
for (let idx = 0; idx < data.length; idx += 4) { data[idx + 3] = Math.round(data[idx + 3] * 0.5); // halve the alpha}Color spaces
Pixel values are stored in the image’s own color space.
Most images are sRGB, but a photo from a phone is often Display P3, and Jimp keeps it that way: image.colorSpace tells you which, and the ICC profile is written back when you save.
See Color spaces for the full picture.
That affects colors in two ways:
- Numbers are raw pixel values.
0xff0000ff,setPixelColor,getPixelColor,image.backgroundand the{ r, g, b }colors ofcolor()are used as they are, in the image’s color space. Reading a pixel and writing it back never changes it. - CSS strings are sRGB, as in a browser, and are converted to the image’s color space. On a Display P3 image,
"#ff0000"becomesrgb(234, 51, 35), the same red you’d see in a browser. Usecolor(display-p3 r g b)for a Display P3 color.
import { Jimp } from "jimp";
const image = new Jimp({ width: 10, height: 10, color: "#ff0000", colorSpace: "display-p3" });
image.getPixelColor(0, 0).toString(16); // "ea3323ff": sRGB red, converted to Display P3Methods that change pixels, such as greyscale, brightness and the color() actions, work on the stored values. exposure is the exception: it uses the image’s tone curves to work in linear light.
To convert the pixels to another space, use toColorSpace.
Transparency
The alpha byte says how opaque each pixel is.
hasAlpha returns true if any pixel’s alpha is below 255:
await image.write(image.hasAlpha() ? "out.png" : "out.jpeg");PNG, TIFF and ICO keep the alpha channel when written, GIF keeps fully transparent pixels, and JPEG and BMP drop it.
Before writing JPEG or BMP, Jimp draws the image over image.background, a color number that is transparent black (0x00000000) for images you read and the fill color for images made with new Jimp({ color }).
Set it to choose what transparent areas turn into:
image.background = 0xffffffff; // white
await image.write("flattened.jpeg");To change alpha across a whole image, use opacity, fade or opaque.
All pixel methods
Read the color of one pixel as an RGBA integer.
Rendering…setPixelColor()Set the color of one pixel from an RGBA integer.
Rendering…getPixelIndex()Get the position of a pixel in the bitmap's data buffer.
hasAlpha()Check whether any pixel is not fully opaque.
Rendering…scan()Run a function for every pixel in the image or a region.
Rendering…scanIterator()Loop over the pixels of the image or a region with for...of.
See also
- Compositing: combining images with blend modes instead of copying pixels.
- Constants and enums:
Edgeand the other enums. - TypeScript: the
Bitmap,RGBAColorandRGBColortypes. - Color spaces: Display P3, ICC profiles and converting between spaces.
- Writing Plugins: package a pixel effect as a reusable method.
- Using in Browser: moving pixels between Jimp and a canvas.