Loading & saving
getBase64()
Encode the image in a format and get it as a base64 data URL.
From @jimp/core
getBase64 encodes the image and returns it as a data: URL, such as data:image/png;base64,iVBORw0KGgo….
Set it as the src of an <img> to show the result in a browser, or embed it in HTML, CSS or JSON.
Signature
image.getBase64(mime: string, options?: EncodeOptions): Promise<string>getBase64 returns a promise for a string. It doesn’t change the image.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
mime |
string |
required | The output format’s MIME type, such as "image/png" or JimpMime.jpeg. |
options |
object |
none | Encoder options for that format, the same as for getBuffer, for example { quality: 80 }. |
Example
import { Jimp } from "jimp";
const image = await Jimp.read("/images/cat.jpg");
image.resize({ w: 300 }).greyscale();
document.querySelector("img")!.src = await image.getBase64("image/jpeg", { quality: 85 });Embed an image in HTML
import { Jimp } from "jimp";
const thumbnail = await Jimp.read("photo.png");thumbnail.scaleToFit({ w: 64, h: 64 });
const html = `<img src="${await thumbnail.getBase64("image/png")}" alt="Thumbnail">`;Get only the base64 text
Some APIs want the base64 data without the data: prefix. Encode with getBuffer and convert it yourself:
const base64 = (await image.getBuffer("image/png")).toString("base64");Notes
- It’s
getBufferplus a prefix.getBase64callsgetBufferwith the same arguments and returns"data:" + mime + ";base64," + data. Everything on that page applies, including how transparency is handled in JPEG and theUnsupported MIME typeerror. - Base64 is a third bigger. It stores 3 bytes in 4 characters. For large images, or for uploading, send the bytes from
getBufferinstead. In the browser,URL.createObjectURL(new Blob([bytes]))also gives you a URL for an<img>without the extra size. - v0 difference. Jimp v0 had
getBase64Async, andgetBase64took a callback. In v1,getBase64returns a promise.