Skip to content
docs
GitHub 4.5M /week v2.2.0
Color

contrast()

Raise or lower the contrast, from -1 to +1.

From @jimp/plugin-color

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

contrast.d.ts
image.contrast(val: number): this

contrast 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

example.ts
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:

example.ts
image.contrast(-0.4);

Try it

Drag the slider to change val.

Try contrast()
image.contrast(0.4)

Adjust the contrast, from -1 (flat gray) to +1 (maximum). 0 leaves the image unchanged.

0.4
Loading Jimp…Drop an image to load it
PNG
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 c becomes 127.5 + factor × (c − 127.5), rounded and clamped to 0–255, where factor = (1 + val) / (1 − val). At 0.5 the factor is 3; at -0.5 it’s 1/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 -1 every channel becomes 128, a flat gray. At +1 channels from 0 to 127 become 0 and channels from 128 to 255 become 255, which reduces the image to at most eight colors.
  • Alpha is unchanged. Only the red, green and blue channels are adjusted.
  • Errors. A val that isn’t a number throws val must be numbers. A value outside -1 to +1 throws val must be a number between -1 and +1.
  • Brightness first? contrast pivots around the middle gray. If the image is too dark or too light overall, adjust brightness or call normalize first.
  • Changed in 2.0: channels are scaled around 127.5 and rounded; before, the middle was 127 and results were rounded down. contrast(-1) now gives 128 instead of 127, and other values change by at most one level.