From 26045c24ba6d20948e2cb769a5d5bb2fa21eb89e Mon Sep 17 00:00:00 2001 From: the1812 Date: Sun, 3 Sep 2023 21:45:45 +0800 Subject: [PATCH] Fix resize params --- src/core/writer/image-compress.ts | 82 +++++++++++++++++-------------- 1 file changed, 45 insertions(+), 37 deletions(-) diff --git a/src/core/writer/image-compress.ts b/src/core/writer/image-compress.ts index f9a6a71..501c85a 100644 --- a/src/core/writer/image-compress.ts +++ b/src/core/writer/image-compress.ts @@ -5,54 +5,62 @@ import type { MetadataConfig } from '../core-config' const getQuality = (size: number) => Math.round(92.647 - 1.683e-6 * size) const CompressedData = Symbol('CompressedData') -let imagePool: ImagePoolType +let imagePool: Promise const initImagePool = async () => { if (imagePool) { return } - const { ImagePool } = await import('@squoosh/lib') - imagePool = new ImagePool(cpus().length) + imagePool = (async () => { + const { ImagePool } = await import('@squoosh/lib') + return new ImagePool(cpus().length) + })() } export type CompressedBuffer = Buffer & { - [CompressedData]: Buffer + [CompressedData]: Promise } export const compressImage = async (buffer: Buffer | CompressedBuffer, resolution?: number) => { await initImagePool() - if (buffer[CompressedData]) { - return buffer[CompressedData] as Buffer - } - const { default: imageInfo } = await import('imageinfo') - const info = imageInfo(buffer) - const resize = (() => { - if (!resolution) { - return undefined - } - if (info.width > resolution) { - return { - width: resolution, - } - } - if (info.height > resolution) { - return { - height: resolution, - } - } - return undefined - })() - const image = imagePool.ingestImage(buffer) + if (!buffer[CompressedData]) { + buffer[CompressedData] = (async () => { + const { default: imageInfo } = await import('imageinfo') + const info = imageInfo(buffer) + const resize = (() => { + if (!resolution) { + return undefined + } + if (info.width > resolution) { + return { + width: resolution, + } + } + if (info.height > resolution) { + return { + height: resolution, + } + } + return undefined + })() + const pool = await imagePool + const image = pool.ingestImage(buffer) - await image.preprocess({ - resize, - }) - const result = await image.encode({ - mozjpeg: { - quality: getQuality(buffer.length), - }, - }) - const resultBuffer = Buffer.from(result.mozjpeg.binary) as CompressedBuffer - buffer[CompressedData] = resultBuffer - return resultBuffer + await image.preprocess( + resize + ? { + resize, + } + : undefined, + ) + const result = await image.encode({ + mozjpeg: { + quality: getQuality(buffer.length), + }, + }) + const resultBuffer = Buffer.from(result.mozjpeg.binary) as CompressedBuffer + return resultBuffer + })() + } + return (buffer as CompressedBuffer)[CompressedData] } export const compressImageByConfig = async ( buffer: Buffer | CompressedBuffer,