From 1eb678cabd5816b81507d6387672593a1399bbf4 Mon Sep 17 00:00:00 2001 From: Kae <80987908+Novaenia@users.noreply.github.com> Date: Sun, 27 Apr 2025 04:10:32 +1000 Subject: Optimize compressImage method to also use binary search (#7490) * use binary search for compressImage * use binary search for doResize (mobile version) * use binary search for doResize (web version) * use safeDeleteAsync in compressImage --------- Co-authored-by: nguyen --- src/lib/media/manip.ts | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) (limited to 'src/lib/media/manip.ts') diff --git a/src/lib/media/manip.ts b/src/lib/media/manip.ts index 7f052068d..f6ef8347d 100644 --- a/src/lib/media/manip.ts +++ b/src/lib/media/manip.ts @@ -178,15 +178,20 @@ async function doResize(localUri: string, opts: DoResizeOpts): Promise { height: imageRes.height, }) - for (let i = 0; i < 9; i++) { - // nearest 10th - const quality = Math.round((1 - 0.1 * i) * 10) / 10 + let minQualityPercentage = 0 + let maxQualityPercentage = 101 // exclusive + let newDataUri + + while (maxQualityPercentage - minQualityPercentage > 1) { + const qualityPercentage = Math.round( + (maxQualityPercentage + minQualityPercentage) / 2, + ) const resizeRes = await manipulateAsync( localUri, [{resize: newDimensions}], { format: SaveFormat.JPEG, - compress: quality, + compress: qualityPercentage / 100, }, ) @@ -198,8 +203,8 @@ async function doResize(localUri: string, opts: DoResizeOpts): Promise { } if (fileInfo.size < opts.maxSize) { - safeDeleteAsync(imageRes.uri) - return { + minQualityPercentage = qualityPercentage + newDataUri = { path: normalizePath(resizeRes.uri), mime: 'image/jpeg', size: fileInfo.size, @@ -207,9 +212,17 @@ async function doResize(localUri: string, opts: DoResizeOpts): Promise { height: resizeRes.height, } } else { - safeDeleteAsync(resizeRes.uri) + maxQualityPercentage = qualityPercentage } + + safeDeleteAsync(resizeRes.uri) } + + if (newDataUri) { + safeDeleteAsync(imageRes.uri) + return newDataUri + } + throw new Error( `This image is too big! We couldn't compress it down to ${opts.maxSize} bytes`, ) -- cgit 1.4.1