const buf1 = await imageToBuffer('data:image/png;base64,iVBOR...');
const buf2 = await imageToBuffer(fs.readFileSync('photo.png'));
const buf3 = await imageToBuffer('https://example.com/photo.png');
const buf4 = await imageToBuffer('/absolute/path/to/image.jpg');
// A URL a model's tool call gave: public hosts only, 50 MiB and 30 s at most.
const buf5 = await imageToBuffer(toolArgs.imageUrl, { untrusted: true });
Converts an image input from any of the supported formats into a
Buffer.Supported input formats:
Buffer— returned as-is.data:image/png;base64,iVBOR...is decoded from base64; one without;base64, such asdata:image/svg+xml,%3Csvg%3E..., is percent-decoded byte by byte./(RFC 4648, Table 1), so a JPEG's base64 begins with/9j/. A missing path is still an error; when the string is base64 of another format, the error says so without repeating the string.file:URL — converted to a local path withfileURLToPathand read.globalThis.fetchand buffered./or\, or ends in a file extension, is read withfs.readFile.A string from an untrusted source can name any file the process can read, and a URL can point at this machine or a private network, a cloud metadata service among them. Pass
{ untrusted: true }for such input: file paths andfile:URLs are refused (raw base64 of a recognised image format is still decoded), and an http(s) URL is fetched only from public network addresses, checked at every connection and every redirect, withinmaxBytesandtimeoutMs. An image decoded from the string is refused when it is larger thanmaxBytes.@param input - The image in any supported format. @param options - {@link ImageToBufferOptions};
untrustedfor input from a model or a user. @returns ABuffercontaining the raw image bytes.@throws {TypeError} When
inputis neither a string nor a Buffer. @throws {RangeError} Withuntrusted, whenmaxBytesis not a positive number. @throws {Error} When a remote URL fetch fails or the file cannot be read; withuntrusted, also when the input names a local file (code: 'IMAGE_LOCAL_FILE_REFUSED'), a URL whose address or redirect is refused (code: 'IMAGE_URL_REFUSED'), or an image larger thanmaxBytes.