Using in Browser
How to use Jimp in the browser.
Jimp can be used anywhere that JavaScript is supported. It can be used in the browser, in Node.js, or in a web worker. Jimp comes with a pre-bundled browser version. To use it simply import jimp instead.
Usage
From a CDN
The browser build at dist/browser/index.js is a self-contained ES module, so you can import it straight from a CDN without a bundler. This page does exactly that.
<script type="module">
import { Jimp } from "https://cdn.jsdelivr.net/npm/jimp@1/dist/browser/index.js";
const image = await Jimp.read("/some/url");
image.greyscale();
document.querySelector("img").src = await image.getBase64("image/png");
</script>
The same file is on unpkg at https://unpkg.com/jimp@1/dist/browser/index.js. jimp@1 always loads the latest v1 release. Pin an exact version such as jimp@1.7.0 to make sure an update never changes your page.
The jimp/fonts export isn't self-contained, so it can't be imported from a CDN. Load your fonts by URL with loadFont instead.
With hosted file
You can initialize a Jimp instance from a URL or a file path.
import { Jimp } from "jimp";
// Read a file hosted on the same domain
const image1 = await Jimp.read("/some/url");
// Read a file hosted on a different domain
const image2 = await Jimp.read("https://some.other.domain/some/url");
With uploaded files
Or you can use Jimp with an ArrayBuffer. Here we take a user's uploaded image and modify it to greyscale. In this app, File › Open Image… (or dropping a file on the canvas) does the same thing.
function handleFile(e) {
const reader = new FileReader();
reader.onload = async (e) => {
const image = await Jimp.fromBuffer(e.target?.result);
image.greyscale();
const base64 = await image.getBase64("image/jpeg");
};
reader.readAsArrayBuffer(e.target.files[0]);
}
input.addEventListener("change", handleFile);
Using Canvas
You can also use Jimp with a canvas.
const canvas = document.getElementById("my-canvas");
const ctx = canvas.getContext("2d");
// Load the canvas into a Jimp instance
const image = await Jimp.fromBitmap(
ctx.getImageData(0, 0, canvas.width, canvas.height)
);
// Manipulate the image
image.greyscale();
const imageData = new ImageData(
new Uint8ClampedArray(image.bitmap.data),
image.bitmap.width,
image.bitmap.height
);
// Write back to the canvas
ctx.putImageData(imageData, 0, 0);
Web Workers
Jimp can be slow and you don't want that running on the main thread. Workers can make this experience a lot better. First define a worker. This is where you should import jimp and do your image transformations.
import { Jimp } from "jimp";
self.addEventListener("message", async (e) => {
const image = await Jimp.fromBuffer(e.data.image);
if (e.data.options.blur) {
image.blur(e.data.options.blur);
}
self.postMessage({ base64: await image.getBase64("image/png") });
});