getPixelColor returns the color of the pixel at x, y as a single number in 0xRRGGBBAA form.
Use it to sample a color, check a pixel’s transparency or compare a few points; pass the result to intToRGBA to get the separate channels.
Signature
image.getPixelColor(x: number, y: number): numbergetPixelColor only reads the image. It returns the color, so it can’t be chained.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x |
number |
required | Column, counted from 0 at the left edge. |
y |
number |
required | Row, counted from 0 at the top edge. |
The return value is an unsigned 32-bit integer from 0x00000000 to 0xffffffff: one byte each for red, green, blue and alpha, in that order.
Example
import { Jimp, intToRGBA } from "jimp";
const image = await Jimp.read("photo.png");
const color = image.getPixelColor(10, 20); // e.g. 0x2f2f92e3
const { r, g, b, a } = intToRGBA(color); // { r: 47, g: 47, b: 146, a: 227 }Show the color as hex
The number prints in decimal by default.
Pad it to eight hex digits to get a CSS-style #rrggbbaa string:
const hex = "#" + image.getPixelColor(10, 20).toString(16).padStart(8, "0");// "#2f2f92e3"Check whether a pixel is transparent
The alpha channel is the lowest byte, so color & 0xff is the pixel’s alpha:
const isTransparent = (image.getPixelColor(0, 0) & 0xff) === 0;Try it
Click the image to pick a pixel. The swatch in the top-left corner is painted with the color getPixelColor returned.
const color = image.getPixelColor(180, 151)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"); // Change an option to run it await image.write("output.png");
Notes
- Coordinates are rounded to the nearest whole pixel, so
getPixelColor(10.4, 19.6)reads pixel(10, 20).setPixelColorrounds the same way, so both always reach the same pixel. - Coordinates outside the image read the nearest edge pixel. They’re clamped (the
Edge.EXTENDbehavior ofgetPixelIndex), sogetPixelColor(-5, 0)returns the color of(0, 0). This keeps code that samples around a pixel, such as a blur, working at the borders. To find out whether a point is inside the image, checkimage.getPixelIndex(x, y, Edge.CROP) !== -1, or comparexandywithimage.widthandimage.height. - Arguments must be numbers. Anything else, including
NaN, throwsx and y must be numbers. - Reading many pixels. Each call computes an index and reads four bytes. To process a whole image,
scanand readingimage.bitmap.datadirectly avoids the extra work. See Colors and pixels. - Raw values. The number is the pixel as stored, in the image’s color space. Writing it back with
setPixelColornever changes the pixel. - Changes from v0. The optional callback argument and the
getPixelColouralias are gone;getPixelColorreturns the value directly. - Changed in 2.0:
NaNcoordinates throw; before, they read pixel(0, 0).