Every online form that asks for a photo also has a size limit: 100 KB for a visa, 200 KB for a job portal, "under 1 MB" for a scholarship. People usually solve it by uploading their passport photo to a random converter site. I build small Android utilities, so I implemented the compression inside the app instead — nothing leaves the phone. The interesting part is not the encoding, it is hitting the byte target exactly, because the runtime I work in (a WebView) has no "compress to N bytes" API.
Quality is not a linear knob. A JPEG encoder takes a quality value and returns whatever size it returns. The curve is flat near the top and steep in the middle, so guessing (90 → 60 → 40) either overshoots the target or throws quality away. A binary search on quality converges in a handful of encodes: start high, measure, move the interval toward the target, and stop at the largest result that still fits under the limit. For the usual 100 KB case that is one or two encodes; for an awkward photo it is five or six, which is still fast enough to feel instant on a phone.
When quality bottoms out, resize. If the smallest acceptable quality still exceeds the target, the dimensions are the problem, not the encoder. Scale down by about 15% and run the search again, with a floor that keeps small print on a document readable. Decoding once at the target size (createImageBitmap(blob, { resizeWidth, resizeHeight })) matters more than anything else here — drawing a 48 MP bitmap into a canvas to shrink it later is how you get an out-of-memory crash on a mid-range phone.
Never overwrite the original. Re-encoding with canvas already drops EXIF, which is what you want for a photo that leaves the phone (no GPS, no camera serial), but the user will not know that when they tap a button. I write the result to a separate file, keep the original in the gallery, and show both sizes afterwards, because the most common complaint about this kind of tool is "where did my photo go".
Batch, memory and PNG. Processing a batch sequentially with one canvas reused is boring and correct; parallel encodes look faster and then the phone kills the app on the 12th photo. PNG needs its own path: re-encoding at a quality value does nothing for PNG, so either convert to JPEG when the image has no transparency or accept a much larger file. Telling the user which one happened is part of the feature.
What people actually ask for. In practice the requests are narrow: an exact preset (100 KB, 200 KB, 500 KB, 1 MB) or an arbitrary number, a pixel size for a visa photo (413×531 is the Korean one), and batch. Video is out of scope, because the same trick does not work on it. If you want to see the result rather than the code, this is the app I ship the pipeline in: Photo Size Reducer – Compress on Google Play. Free, Android only, ads, and every step above runs on the device.