diff --git a/src/lib/server/image.ts b/src/lib/server/image.ts new file mode 100644 index 0000000..d3ba3a6 --- /dev/null +++ b/src/lib/server/image.ts @@ -0,0 +1,23 @@ +import sharp from "sharp"; + +/** + * Convert any [ArrayBuffer] containing image data to an [avif] [Blob]. + * Also allows downscaling and lossy compression. + * Set either [width] or [height] to downscale while keeping the aspect ratio. + */ +export const image_to_avif = async ( + data: ArrayBuffer, + width: number | undefined = undefined, + height: number | undefined = undefined, + quality: number = 50, + effort: number = 4, +): Promise => { + const compressed: Buffer = await sharp(data) + .resize(width, height) + .avif({ quality: quality, effort: effort }) + .toBuffer(); + + console.log(`image_to_avif: ${data.byteLength} Bytes -> ${compressed.length} Bytes`); + + return new Blob([compressed]); +};