getBuffer()
Encode the image in a format and get the bytes as a Buffer.
From @jimp/core
getBuffer encodes the image as a PNG, JPEG or other format and gives you the bytes.
Use it whenever the image goes somewhere other than a local file: an HTTP response, cloud storage, a database or a Blob in the browser.
Signature
image.getBuffer(mime: string, options?: EncodeOptions): Promise<Buffer>getBuffer returns a promise for a Buffer with the encoded file. It doesn’t change the image, so you can encode the same image several times.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
mime |
string |
required | The output format’s MIME type, such as "image/png". Use JimpMime to avoid typos. |
options |
object |
none | Encoder options for that format. Which options are allowed depends on mime; see Options below. |
Example
import { Jimp, JimpMime } from "jimp";
const image = await Jimp.read("photo.png");
image.resize({ w: 800 });
const jpeg = await image.getBuffer(JimpMime.jpeg, { quality: 80 });
console.log(jpeg.length); // the file size in bytesSend an image from a server
import { createServer } from "node:http";import { Jimp } from "jimp";
createServer(async (req, res) => { const image = await Jimp.read("avatar.png");
image.cover({ w: 128, h: 128 });
res.setHeader("Content-Type", "image/png"); res.end(await image.getBuffer("image/png"));}).listen(3000);Download in the browser
In the browser the result is a Uint8Array subclass, so it can go straight into a Blob:
const bytes = await image.getBuffer("image/png");const url = URL.createObjectURL(new Blob([bytes], { type: "image/png" }));
const link = document.createElement("a");link.href = url;link.download = "edited.png";link.click();For an <img src>, getBase64 is often simpler.
Choosing the format
The first argument is a MIME type string. The default jimp package can encode these:
| Format | MIME type | JimpMime constant |
|---|---|---|
| PNG | "image/png" |
JimpMime.png |
| JPEG | "image/jpeg" |
JimpMime.jpeg |
| GIF | "image/gif" |
JimpMime.gif |
| BMP | "image/bmp", "image/x-ms-bmp" |
JimpMime.bmp |
| TIFF | "image/tiff" |
JimpMime.tiff |
| ICO | "image/x-icon", "image/vnd.microsoft.icon" |
JimpMime.ico |
An image read from a file remembers its format in image.mime, in case you want to encode it the same way.
WebP, AVIF, JPEG XL and JPEG 2000 need a custom Jimp with the WASM format plugins; see Formats.
Options
The options depend on the format. With TypeScript, the type of options follows the mime you pass, so options for the wrong format are a type error. GIF and TIFF take no options at all.
JPEG
Type: JPEGOptions.
| Option | Type | Default | Description |
|---|---|---|---|
quality |
number |
100 |
Compression quality from 1 (smallest file, most artifacts) to 100 (largest, best). Values below 1 count as 1 and values above 100 as 100. |
chromaSubsampling |
"4:4:4" | "4:2:2" | "4:2:0" |
"4:2:0" below quality 90, else "4:4:4" |
How much to reduce the resolution of the color channels, which the eye is less sensitive to: not at all, by half horizontally, or by half both ways, which makes photos much smaller. |
progressive |
boolean |
false |
Write a progressive JPEG, which browsers show at a low quality first and refine as it loads. Usually a few percent smaller, but slower to encode and decode. |
exif |
boolean |
false |
Write the EXIF data of the JPEG the image was read from, with the orientation and size updated. See EXIF. |
icc |
boolean |
true |
Write the image’s ICC profile, such as Display P3. false writes sRGB without a profile, converting the colors first. See Color Spaces. |
const photo = await Jimp.read("camera.jpg");
photo.resize({ w: 1600 });
const small = await photo.getBuffer("image/jpeg", { quality: 75, exif: true });const forTheWeb = await photo.getBuffer("image/jpeg", { quality: 80, progressive: true,});PNG
Type: PNGOptions, exported from @jimp/js-png. The encoder is @jimp/pngjs, Jimp’s fork of pngjs; these are the options worth setting:
| Option | Type | Default | Description |
|---|---|---|---|
colorType |
PNGColorType |
smallest lossless | The pixel layout. By default Jimp picks the smallest one that loses nothing: a palette if the image has 256 colors or fewer, gray if every pixel is gray, no alpha channel if every pixel is opaque. PNGColorType.PALETTE needs 256 colors or fewer. |
filterType |
PNGFilterType |
PNGFilterType.AUTO |
The row filter applied before compression. AUTO tries each filter on every row and keeps the best. Palette and 1, 2 and 4-bit images use NONE unless you set it, as filters rarely help them. |
deflateLevel |
number |
9 |
zlib compression level, 0 (none) to 9 (smallest). |
deflateStrategy |
number |
3 |
zlib strategy: 0 default, 1 filtered, 2 Huffman only, 3 run-length, 4 fixed. |
bitDepth |
1 | 2 | 4 | 8 | 16 |
smallest lossless | Bits per channel, or per palette index. Gray images whose levels allow it are written at 1, 2 or 4 bits. 16 makes the file bigger without adding precision, as Jimp’s pixels have 8 bits per channel. |
bgColor |
object |
white | { red, green, blue }, 0 to 255. When colorType has no alpha channel, transparent pixels are blended onto this color. |
icc |
boolean |
true |
Write the image’s ICC profile, as for JPEG. |
inputHasAlpha |
boolean |
Deprecated. false is the same as colorType: PNGColorType.COLOR; true does nothing. |
The values of colorType and filterType are the PNGColorType and PNGFilterType enums, exported from jimp.
import { Jimp, PNGColorType } from "jimp";
const image = await Jimp.read("logo.png");
// Drop the alpha channel, putting transparent areas on whiteconst flat = await image.getBuffer("image/png", { colorType: PNGColorType.COLOR });With the default deflateStrategy of 3, deflateLevel makes almost no difference to the size.
For the smallest PNGs, set deflateStrategy: 1 with deflateLevel: 9. The file is usually a little smaller, and encoding takes several times longer.
BMP
Type: EncodeOptions, exported from jimp. Jimp writes uncompressed BMPs.
| Option | Type | Default | Description |
|---|---|---|---|
bitPP |
1 | 4 | 8 | 16 | 24 | 32 |
24 |
Bits per pixel. 24 stores 8 bits each of red, green and blue. 16 stores 5 bits each, for a smaller file with less color precision. 32 adds an alpha byte, which is always opaque because BMPs are drawn over the background. 1, 4 and 8 store an index into a palette of up to 2, 16 or 256 colors. |
palette |
(number | string)[] |
picked from the image | The colors of a 1, 4 or 8-bit BMP, as 0xRRGGBBAA numbers or CSS colors: up to 2, 16 or 256 of them. Each pixel is written as the palette color nearest to it in RGB. Alpha is ignored. Not used for 16, 24 and 32-bit BMPs. |
hr |
number |
0 |
Horizontal resolution, in pixels per meter (2835 is about 72 DPI). |
vr |
number |
0 |
Vertical resolution, in pixels per meter. |
reserved1, reserved2 |
number |
0 |
Values for the header’s two reserved fields, which readers ignore. |
const small = await image.getBuffer("image/bmp", { bitPP: 16 });
// A 4-bit BMP with four colorsconst indexed = await image.getBuffer("image/bmp", { bitPP: 4, palette: ["black", "white", "#ff0000", 0x0000ffff],});Without palette, an image with few enough colors is written with exactly those colors. Otherwise:
- 1-bit BMPs are black and white: pixels whose Rec. 709 luminance is above
127.5are white. - 4 and 8-bit BMPs get a palette of the image’s most important colors, picked with Wu’s quantization algorithm.
Pixels aren’t dithered. For a dithered result, call dither or quantize first:
image.dither({ type: "floyd-steinberg" }); // black and white, dithered
const bw = await image.getBuffer("image/bmp", { bitPP: 1 });Any other bitPP throws, for example Unsupported BMP bit depth 7, use 1, 4, 8, 16, 24, 32. A palette with too many colors, or an empty one, throws, for example A 4-bit BMP palette needs 1 to 16 colours, got 20.
ICO
Type: EncodeIcoOptions, exported from @jimp/js-ico. Jimp writes each image in the icon as a 32-bit PNG, so transparency is kept.
| Option | Type | Default | Description |
|---|---|---|---|
sizes |
number[] |
none | Write one image per size, each scaled to fit in a square of that size with the aspect ratio kept, for example [16, 32, 48, 256]. Sizes are clamped to 1 to 256. Without it, the icon holds the image itself, scaled down to fit in 256 × 256 if it’s larger. |
const logo = await Jimp.read("logo.png"); // square images make square icons
const icon = await logo.getBuffer("image/x-icon", { sizes: [16, 32, 48] });The image itself isn’t resized; each size is scaled from a copy.
GIF and TIFF
These encoders take no options. GIF output is a single frame with at most 256 colors. TIFF output is uncompressed RGBA.
WASM formats
The WASM format plugins have their own options, such as quality and lossless for WebP (which also takes icc), or compressionRatio for JPEG 2000. See Formats.
Try it
Pick a format to see what encoding does to the image: JPEG’s artifacts as you lower quality, GIF’s limited palette, and what happens to the transparent background in formats without transparency.
image.bitmap = (await Jimp.fromBuffer(await image.getBuffer("image/jpeg", { quality: 10 }))).bitmapEncode the image in a format and decode it again, to see what the format keeps: JPEG quality loss, GIF's 256 colors, lost transparency, ICO's 256 pixel limit.
import { Jimp } from "jimp"; const image = await Jimp.read("dice.png"); // Change an option to run it await image.write("output.png");
Notes
- Transparency in formats without it. Before encoding JPEG, BMP, GIF or TIFF, Jimp draws the image over
image.background. The default background is transparent black, so fully transparent pixels come out black in a JPEG or BMP. Setimage.background = 0xfffffffffirst to put them on white instead. PNG, ICO and most WASM formats skip this step and keep the alpha channel. - Color profiles. JPEG, PNG and WebP output keeps the image’s ICC profile. Other formats can’t carry one, so for an image in another color space, such as Display P3, Jimp encodes a copy converted to sRGB. Images without a profile are written as they are. See Color Spaces.
- Errors. A MIME type the image can’t encode throws
Unsupported MIME type: image/webp. That includes typos and MIME types of formats you haven’t added. - Only JPEG output can carry EXIF. Other formats never include it, and the
exifoption is a type error for them. - The image isn’t modified. Even when the image is drawn over its background or converted to sRGB, that happens on a copy.
- Added in 2.0: JPEG’s
exifandiccoptions, PNG and WebP’siccoption, BMP’sbitPPandpaletteoptions, and the ICO format. - Changed in 2.0: without
colorType, PNGs are written with the smallest lossless color type instead of always RGBA. GIFs with more than 256 colors are quantized differently, in constant memory. - Changed in 2.0: BMP’s
colorsandimportantColorsoptions, and the oldpaletteof{ red, green, blue, quad }objects, are removed; they had no effect. PNG’swidth,height,fill,checkCRC,skipRescale,deflateFactoryanddeflateChunkSizeencode options are removed too. In TypeScript, GIF and TIFF take no options.