limit255 clamps a number so it’s at least 0 and at most 255, the range of one color channel.
Use it whenever you compute a new channel value, before writing it to image.bitmap.data or passing it to rgbaToInt.
Signature
import { limit255 } from "jimp";
limit255(n: number): numberParameters
| Parameter | Type | Default | Description |
|---|---|---|---|
n |
number |
required | The value to clamp. |
Example
import { limit255 } from "jimp";
limit255(300); // 255limit255(-20); // 0limit255(128); // 128limit255(12.7); // 12.7, not roundedBrighten an image
Without limit255, a channel value of 200 + 80 = 280 would be stored as 24, turning the brightest areas dark.
import { Jimp, limit255 } from "jimp";
const image = await Jimp.read("photo.png");
image.scan((x, y, idx) => { const { data } = image.bitmap; data[idx] = limit255(data[idx] + 80); data[idx + 1] = limit255(data[idx + 1] + 80); data[idx + 2] = limit255(data[idx + 2] + 80);});Try it
Change amount, then turn “use limit255” off to see what happens when values above 255 or below 0 are written without clamping: they wrap around.
image.scan((x, y, idx) => {Add a value to every color channel. Turn limit255 off to see values above 255 wrap around to 0.
use limit255
Loading Jimp…Drop an image to load it
index.js
import { Jimp } from "jimp"; const image = await Jimp.read("dice.png"); // Change an option to run it await image.write("output.png");
Notes
- Why it’s needed.
image.bitmap.datais aBuffer, which stores each value modulo 256:256becomes0,300becomes44and-1becomes255. It never throws, so mistakes show up as strange colors. - It doesn’t round. Fractions pass through unchanged. When a
Bufferstores a fraction it drops the fractional part, so wrap the value inMath.roundfirst if you want rounding:limit255(Math.round(n)). NaNstaysNaN, which aBufferstores as0.- Changes from v0.
limit255used to be a static method,Jimp.limit255. It’s now a named export ofjimp(and of@jimp/utils).