make optimization slightly less wonky?

This commit is contained in:
john 2025-05-26 22:17:49 +02:00
parent 48f1b873a5
commit f147933701

View file

@ -185,6 +185,7 @@ async function optimizeImageSize(
const scale = Math.min(1, targetMaxWidth / img.width, targetMaxHeight / img.height)
const width = Math.floor(img.width * scale)
const height = Math.floor(img.height * scale)
const originalSize = file.size
const srcCanvas = document.createElement('canvas')
srcCanvas.width = img.width
@ -200,10 +201,14 @@ async function optimizeImageSize(
let blob = await pica.toBlob(dstCanvas, outputType, quality)
while (blob.size > targetSizeBytes && quality > 0.1) {
quality = parseFloat((quality - 0.1).toFixed(2))
quality -= 0.1
blob = await pica.toBlob(dstCanvas, outputType, quality)
}
console.debug(
`optimized image rendered at ${Math.round(quality * 100)}% quality to ${blob.size / 1000}KB from ${originalSize / 1000}KB`,
)
URL.revokeObjectURL(url)
return new File([blob], file.name, { type: file.type })