Jimp getBase64: image to data URI

Jimp can read an image, process it, and export a Base64 data URI. In the official core implementation checked on October 8, 2026, getBase64() returns a Promise, so use await. The resolved value already contains the header, such as data:image/png;base64,....

For a one-off conversion without installing a library, use the Image to Base64 tool. Jimp is useful when your Node.js workflow also needs to resize or re-encode an image before producing the text output.

Jimp decodes files with its own codecs, so the pipeline needs no DOM, no canvas element, and no headless browser. That is the practical difference from the browser route: FileReader and canvas.toDataURL() both assume a page, and a cron job, queue worker, or CLI script has none. The same call works inside a long-running service and inside a throwaway script.

What getBase64 returns

await image.getBase64("image/png") returns a complete PNG data URI. That string can be assigned to a browser <img src> or used where the destination explicitly accepts data URIs.

An API field documented as “Base64 content” may instead expect only the text after the comma. Check the destination's contract before sending it. The API output-shape guide covers raw Base64 versus a full data URI.

The export comes in two shapes, and swapping them explains most rejected payloads. getBase64(mime) resolves to a string that already carries the media type and the comma. The buffer path resolves to encoded bytes with no prefix at all: older releases spell the pair getBase64Async(Jimp.MIME_PNG) and getBufferAsync, current ones accept a MIME string. On the buffer path nothing inserts data:image/png;base64, for you, so you either concatenate the prefix or send the bare text, depending on what the receiver documents.

Vision endpoints are a frequent destination for these strings, and they usually want the payload without a header; the OpenAI vision Base64 image guide shows the shape those requests take.

Complete Node.js example

Install Jimp in your own project if it is not already a dependency, then save this as jimp-data-uri.mjs. Run it with node jimp-data-uri.mjs input.png. The script writes a data URI and a raw Base64 file so you can choose the output your destination needs.

import { Jimp } from "jimp";
import { writeFile } from "node:fs/promises";

const input = process.argv[2];
if (!input) throw new Error("Usage: node jimp-data-uri.mjs input.png");

const image = await Jimp.read(input);
// Optional processing before export:
// image.resize({ w: 320 });
const dataUri = await image.getBase64("image/png");
const prefix = "data:image/png;base64,";
if (!dataUri.startsWith(prefix)) throw new Error("Unexpected PNG data URI");
const rawBase64 = dataUri.slice(prefix.length);

await writeFile("image.data-uri.txt", dataUri, "utf8");
await writeFile("image.base64.txt", rawBase64, "utf8");
console.log(`Wrote ${dataUri.length} data-URI characters.`);

Keeping both outputs side by side means you can paste the right one instead of trimming a value by hand and leaving a stray newline or a duplicated header behind. Most APIs want the raw string; an <img> tag or a CSS rule wants the prefix.

This example exports PNG even if the input is a supported JPEG. Use image/jpeg and the options supported by your installed Jimp version when you want JPEG output. PNG and JPEG differ in transparency and compression; a Base64 string does not erase those differences. See image resizing before Base64 when payload size matters.

Memory cost of decoding an image you never edit

Jimp.read() decodes the file into an RGBA bitmap before any export runs. A 4000 x 3000 photograph therefore occupies about 48 MB of heap while the compressed PNG on disk may be 3 MB, because every pixel carries four bytes. Four of those in flight inside one worker is roughly 200 MB of bitmaps, which is where container memory limits usually get hit.

Batch scripts should set their own concurrency rather than mapping over a directory. When the job only moves bytes — upload, attachment, JSON field — the decoder earns nothing: readFile() keeps just the compressed file in memory and produces the same Base64 text from the same bytes. The Base64 size calculator estimates the output length before you encode, so an oversized payload is caught before it reaches a memory limit or an API's request cap.

Read a data URI back into Jimp

For a trusted data URI produced by the previous script, remove the prefix and decode its Base64 payload into a Buffer. Save the following as jimp-read-data-uri.mjs:

import { Jimp } from "jimp";
import { readFile } from "node:fs/promises";

const dataUri = (await readFile("image.data-uri.txt", "utf8")).trim();
const match = /^data:image\/(?:png|jpeg);base64,([A-Za-z0-9+/]+={0,2})$/.exec(dataUri);
if (!match) throw new Error("Expected a PNG or JPEG Base64 data URI");
const bytes = Buffer.from(match[1], "base64");
if (!bytes.length || bytes.toString("base64") !== match[1]) {
  throw new Error("Invalid Base64 payload");
}
const image = await Jimp.fromBuffer(bytes);
console.log(image.bitmap.width, image.bitmap.height);

This is a local-file example. For untrusted uploads, also enforce encoded-byte and decoded-pixel limits before processing. A compressed file can be small while its decoded bitmap is large.

Preserve the original bytes when you do not need editing

Jimp's getBase64() calls its image encoder. It does not promise byte-for-byte preservation of the source file or its metadata. If you only need Base64 of the original bytes, Node's standard library is enough:

import { readFile } from "node:fs/promises";
const rawBase64 = (await readFile("input.png")).toString("base64");
const dataUri = `data:image/png;base64,${rawBase64}`;
console.log(dataUri);

Use the MIME type that actually matches the input. For browser-side byte encoding, how to convert an image to Base64 shows the FileReader path.

Byte-level encoding also keeps what a decoder may rewrite: EXIF fields, embedded color profiles, and the exact compression settings. Whether that counts as fidelity or as a leak depends on the file. A camera JPEG carries GPS coordinates that a support inbox should not receive; in most setups re-encoding drops those tags, while the readFile route ships them unchanged. Scans show the same split, since a TIFF carries page structure as well as pixels.

The trade is that this route cannot resize, crop, rotate, or change format. Choose by whether the image needs editing at all, not by which snippet looks shorter. If the string then lands in a request body, the Base64 in JSON APIs guide covers escaping and field size.

Troubleshooting and version differences

I see [object Promise]. Await getBase64(). Do not pass its Promise directly to an <img> or JSON payload.

My API rejects the string. Check whether it expects raw Base64 rather than a data URI. Do not encode an already encoded Base64 string again.

An old example uses a callback. Match the example to your installed Jimp version. Current named imports and Promise methods should not be combined with an older callback tutorial.

The output file differs from the input. That is expected when Jimp decodes and re-encodes the image. Use readFile().toString("base64") when exact original-byte transport is the requirement.

It works locally and fails at the receiver. Log the first 40 characters and the total length before sending. A data URI prefix where the API wants raw text, a newline picked up from an editor, or a truncated string explains most of these; fixing invalid Base64 image data walks through that diagnosis step by step.

Two questions that come up in review

Does the exported file have to be byte-identical to the source?

No, and usually it is not. getBase64() runs the encoder again, so PNG output can differ in length and metadata even when the pixels look the same. When byte identity matters — a checksum the receiver verifies, a legal archive, a content hash — use the readFile route instead.

Will the same code run in a browser bundle?

Not reliably. Bundling guidance differs by release and by bundler, and the examples here target the Node runtime that Jimp documents first. If the code already runs in a page, FileReader is shorter and adds no dependency.

Related guides

Continue with API payload formats, resizing an image before encoding, or the browser conversion walkthrough.