contrast pushes the color channels of every pixel away from, or toward, the middle value.
Positive values make light areas lighter and dark areas darker; negative values flatten the image toward gray.
Signature
image.contrast(val: number): thiscontrast changes the image in place and returns it, so you can chain more calls after it.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
val |
number |
required | A number from -1 to +1. 0 changes nothing, +1 is maximum contrast and -1 is flat gray. |
Example
import { Jimp } from "jimp";
const image = await Jimp.read("photo.jpg");
image.contrast(0.3);
await image.write("photo-contrast.jpg");Soften an image
A negative value lowers the contrast, which gives a washed-out look:
image.contrast(-0.4);Try it
Drag the slider to change val.
image.contrast(0.4)Adjust the contrast, from -1 (flat gray) to +1 (maximum). 0 leaves the image unchanged.
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
- How it’s computed. Each channel
cbecomes127.5 + factor × (c − 127.5), rounded and clamped to0–255, wherefactor = (1 + val) / (1 − val). At0.5the factor is3; at-0.5it’s1/3. Halves round away from the middle, so dark and light channels are treated alike: inverting and then raising the contrast gives the same result as raising the contrast and then inverting. - The ends of the range. At
-1every channel becomes128, a flat gray. At+1channels from0to127become0and channels from128to255become255, which reduces the image to at most eight colors. - Alpha is unchanged. Only the red, green and blue channels are adjusted.
- Errors. A
valthat isn’t a number throwsval must be numbers. A value outside-1to+1throwsval must be a number between -1 and +1. - Brightness first?
contrastpivots around the middle gray. If the image is too dark or too light overall, adjustbrightnessor callnormalizefirst. - Changed in 2.0: channels are scaled around
127.5and rounded; before, the middle was127and results were rounded down.contrast(-1)now gives128instead of127, and other values change by at most one level.