Add toUint8Array for output backed by transferable ArrayBuffer #4355

This commit is contained in:
Lovell Fuller
2025-12-22 15:05:33 +00:00
parent e1bad5470e
commit dbcb7e60bd
10 changed files with 161 additions and 5 deletions

View File

@@ -164,6 +164,41 @@ function toBuffer (options, callback) {
return this._pipeline(is.fn(options) ? options : callback, stack);
}
/**
* Write output to a `Uint8Array` backed by a transferable `ArrayBuffer`.
* JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported.
*
* Use {@link #toformat toFormat} or one of the format-specific functions such as {@link #jpeg jpeg}, {@link #png png} etc. to set the output format.
*
* If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output.
*
* By default all metadata will be removed, which includes EXIF-based orientation.
* See {@link #keepexif keepExif} and similar methods for control over this.
*
* Resolves with an `Object` containing:
* - `data` is the output image as a `Uint8Array` backed by a transferable `ArrayBuffer`.
* - `info` contains properties relating to the output image such as `width` and `height`.
*
* @since v0.35.0
*
* @example
* const { data, info } = await sharp(input).toUint8Array();
*
* @example
* const { data } = await sharp(input)
* .avif()
* .toUint8Array();
* const base64String = data.toBase64();
*
* @returns {Promise<{ data: Uint8Array, info: Object }>}
*/
function toUint8Array () {
this.options.resolveWithObject = true;
this.options.typedArrayOut = true;
const stack = Error();
return this._pipeline(null, stack);
}
/**
* Keep all EXIF metadata from the input image in the output image.
*
@@ -1659,6 +1694,7 @@ module.exports = (Sharp) => {
// Public
toFile,
toBuffer,
toUint8Array,
keepExif,
withExif,
withExifMerge,