Hitting Exact Target-KB Image Budgets and Routing HEIC/AVIF Locally in Web Workers
"Compress this image under 200 KB" is one of the most common form-upload requirements on the web—yet guesswork quality sliders almost always overshoot the byte budget or turn text unreadable. When building Compress Image and Convert Image in FileMinto, we avoided guessing file sizes from lossy quality presets and moved encoding into dedicated Web Workers ( 0 B uploaded ). 1. Sniffing ISO BMFF…
Achieving image compression under 200 KB is a frequent demand on the web, but traditional guesswork quality sliders typically exceed the byte limit or degrade readability. At FileMinto, we avoided reliance on lossy quality presets by relocating encoding tasks to dedicated Web Workers (0 B uploaded).
First, we analyze ISO BMFF containers instead of depending on file extensions, as phones often export .heic or .avif photos with blank or incorrect MIME types. To determine the appropriate decoder (images.mjs), we read the initial 128 bytes (file.slice(0, 128).arrayBuffer()) and examine the ISO BMFF ftyp box for avif, avis, or other brands.
Heic, heix, hevc, mif1, and msf1 formats trigger an isolated HEIC-to-JPEG Web Worker (workers/heic-to-jpg.js) as needed. PNG-to-ICO packaging uses a separate multi-size icon Worker (workers/png-to-ico.mjs) for processing.
Every job executes its Web Worker within an AbortController, allowing for immediate cancellation of a batch by calling worker.terminate() without memory leaks.
In compressTarget (engines/compress-target.mjs), we confirm success by strictly checking if blob.size equals targetBytes. If the original format, dimensions, and framing already align with the target size, we retain the original bytes (unchanged: true) to prevent unnecessary loss. Otherwise, we render using OffscreenCanvas within the Worker (createImageBitmap + imageSmoothingQuality = 'high') and perform a bounded binary search over encoded bytes in the range [0.1, 0.95] through 8 iterations.
If quality = 0.1 still surpasses targetBytes (and resizing is permitted), we conservatively reduce dimensions up to 6 bounded passes, adjusting the ratio using the formula Math.max(64 / Math.max(w, h), Math.min(0.8, Math.sqrt(targetBytes / size) * 0.9)) until the exact byte cap is achieved.
Lastly, batch ZIP downloads occur in memory once a batch finishes in AssetStore, creating a single archive for instant download. Large photo batches are processed locally without ever uploading data to a backend server. For instance, Compress Image achieves a 200 KB limit in just 21 seconds (21s browser demo) and Convert HEIC, AVIF, PNG & WebP completes in 25 seconds (25s browser demo).
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to