Loading & saving
clone()
Copy the image so you can change the copy and keep the original.
From @jimp/core
clone makes an independent copy of an image.
Image methods change the image they’re called on, so clone first whenever you need the original as well as the edited version: several sizes from one upload, a before and after, or a patch to draw back on top.
Signature
image.clone(): Jimpclone is synchronous. It returns a new image and leaves the original unchanged.
Example
import { Jimp } from "jimp";
const image = await Jimp.read("photo.jpg");
const thumbnail = image.clone().resize({ w: 150 });const preview = image.clone().resize({ w: 800 }).blur(2);
await thumbnail.write("thumb.jpg");await preview.write("preview.jpg");await image.write("original.jpg"); // still full size and sharpEdit part of an image
Clone, edit the copy, then draw it back onto the original:
const area = { x: 40, y: 30, w: 120, h: 120 };
const patch = image.clone().crop(area).pixelate(10);
image.composite(patch, area.x, area.y);Why you need it
Methods return the same image they were called on, not a copy, so assigning the result doesn’t keep the original:
const small = image.resize({ w: 100 });
small === image; // true: `image` was resized tooSee Chaining and async for more.
Notes
- What’s copied. The pixel data and size, the MIME type (
image.mime), thebackgroundcolor, the ICC color profile and the EXIF data. SogetBuffer("image/jpeg", { exif: true })works on a clone of a JPEG too, and a clone of a Display P3 photo is still Display P3. - Cost. Cloning copies every pixel: 4 bytes per pixel, so about 48 MB for a 12-megapixel photo. Clone once and reuse the copy rather than cloning in a loop. If you only need a smaller version, resize a clone once and work from that.
- Same class. A clone of an image from a custom Jimp has the same plugins and formats as the original.
- Changed in 2.0:
clonecopiesmime,background, the EXIF data and the ICC profile. Before, the clone’smimewasundefined, its background was reset to transparent and it had no EXIF data.