crop keeps a rectangle of the image and throws the rest away.
The image becomes the size of the rectangle.
Signature
image.crop(options: { x: number; y: number; w: number; h: number }): thiscrop changes the image in place and returns it, so you can chain more calls after it.
Options
| Option | Type | Default | Description |
|---|---|---|---|
x |
number |
required | The left edge of the rectangle, in pixels from the left. |
y |
number |
required | The top edge of the rectangle, in pixels from the top. |
w |
number |
required | The width of the rectangle in pixels. |
h |
number |
required | The height of the rectangle in pixels. |
All four values are rounded to whole pixels. The rectangle is clamped to the image, so the result is never larger than the image.
Example
import { Jimp } from "jimp";
const image = await Jimp.read("photo.jpg");
image.crop({ x: 100, y: 50, w: 400, h: 300 });
await image.write("photo-cropped.jpg");Crop the center
Work out the offsets from the image size:
const size = Math.min(image.width, image.height);
image.crop({ x: (image.width - size) / 2, y: (image.height - size) / 2, w: size, h: size,});cover does the same and resizes in one call: image.cover({ w: 200, h: 200 }).
Keep the original
crop changes the image it’s called on. To cut out a piece and keep the full image, crop a clone:
const piece = image.clone().crop({ x: 0, y: 0, w: 100, h: 100 });Try it
Drag on the image to choose the rectangle. The code panel shows the matching crop call.
image.crop({ x: 72, y: 54, w: 216, h: 162 })Cut out a rectangle. Drag on the image to choose it.
region
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
- Out-of-bounds rectangles are clamped. Only the part of the rectangle inside the image is kept. On an 800 × 600 image,
crop({ x: 700, y: 0, w: 200, h: 200 })gives a 100 × 200 image, and a negativexorystarts at the edge. - Empty rectangles throw. If nothing would be left, because the rectangle is entirely outside the image or
worhis0or less,cropthrows an error such asThe crop region (x: 10, y: 10, w: 2, h: 2) doesn't overlap the 4x3 image, so the result would be empty. - Removing borders. To trim a plain border without measuring it yourself, use
autocrop, orautocropRectto get the rectangle first. - Missing values. Every option is required. Leaving one out fails validation with
Invalid input: expected number, received undefined. - Changed in 2.0: the rectangle is clamped to the image, and an empty result throws. Before, a rectangle past the edge threw a
RangeError, wrapped pixels from the next row, or left the image with too little pixel data. Cropping is also faster, because whole rows are copied at once. - v0 differences. v0 took positional arguments:
crop(x, y, w, h). In v1 pass an object.