"File too large." Discord's free limit is 10 MB, WhatsApp's is 16 MB, most e-mail stops at 25 MB. Everyone has re-exported a video three times, guessing at a bitrate, to get under one of those numbers.
DotMorph 2.2 has three new tools in the wheel: ≤ 10 MB, ≤ 16 MB and ≤ 25 MB, plus --fit 8M on the command line for any other limit. They work on photos, PDFs, videos and MP3 / M4A / OGG / Opus audio. This post is about how each one finds the best quality that still fits, because "make it small" is easy and "make it just small enough" is not.
Three rules
Before any math, the tools follow three rules that matter more than the algorithms:
- The result is at or under the limit. Not "about". Every path checks the real file size on disk before handing it back.
-
A file that already fits comes back untouched. No re-encode, no quality loss: it's copied as it is (
photo-10mb.jpgis byte for byte the original). - If it can't be done without ruining the file, say so. An hour of 4K video doesn't fit in 10 MB. Writing a 10 MB smear and calling it success would be worse than an error that explains why.
Photos: binary search on quality
For JPEG, WebP and AVIF, file size grows with the quality setting. I measured it on a 12-megapixel test image (generated noise and gradients, which compress like a photo; flat screenshots would make the numbers look too good):
The curve only goes up. That's all a binary search needs: try the middle quality, keep the upper half if it fits, the lower half if it doesn't.
lo, hi, best = 35, 95, None
while lo <= hi:
q = (lo + hi) // 2
save_image(frame, dest, target, replace(opts, quality=q), exif=exif)
if dest.stat().st_size <= limit:
best, lo = q, q + 1 # fits: try better
else:
hi = q - 1 # too big: go lower
With a 2 MB limit it went 65 → 80 → 88 → 92 (too big) → 90 → 91 and stopped at quality 91, 1.997 MB. Six encodes instead of trying all 61 qualities, 2.7 seconds for a 12 MP image.
If even quality 35 is too big, quality isn't the problem: there are too many pixels. Then the image is scaled to 80% and the search runs again, up to 12 times:
for step in range(12):
frame = im if scale == 1.0 else im.resize(
(round(im.width * scale), round(im.height * scale)), Image.LANCZOS)
... # the binary search above
scale *= 0.8
raise too_big(limit, "image") # "can't get this image under 0.2 MB without ruining it"
PNG has no quality knob, so its ladder is different: save it losslessly, and if that's too big, reduce it to a 256-colour palette (which is often a fraction of the size for screenshots), and only then give up pixels.
Video: the budget comes from the length
A video's size is (almost) bitrate × duration. So you don't search for a video's size, you calculate it:
budget = limit * 8 / 1000 / total * 0.96 # kbit/s for everything, minus ~4% container
audio = 96 if budget > 600 else 64 if budget > 250 else 32
video = budget - audio
For 10 MB and a 60-second clip, that's 1,280 kbit/s in all: 96 for the sound, the rest for the picture. If the video budget drops below 60 kbit/s, there's nothing watchable left, and DotMorph says so with the numbers, for example "45 min of video is too long to fit in 10 MB".
Resolution follows the budget, because 1080p at 500 kbit/s looks worse than 480p at 500 kbit/s:
height = None if video > 1800 else 720 if video > 700 else 480 if video > 300 else 360
Why two passes
Normal encodes use a constant quality (CRF), which is the right choice for quality and the wrong one here: the size is whatever the content needs. Single-pass average bitrate is closer, but x264 has to guess how to spend bits before it has seen the rest of the video, and it overshoots. Two-pass fixes that: pass 1 only analyses the video and writes a log; pass 2 uses it to put the bits where they matter and land on the target.
rate = ["-b:v", f"{int(video_kbps)}k", "-maxrate", f"{int(video_kbps * 1.5)}k",
"-bufsize", f"{int(video_kbps * 2)}k"]
# pass 1: analyse only, no audio, output thrown away
self._ffmpeg(src, ["-map", "0:V:0", *vf, *codec, *rate, "-pass", "1",
"-passlogfile", log, "-an", "-f", "null"], Path(os.devnull), ...)
# pass 2: the real file
self._ffmpeg(src, [*maps, *vf, *codec, *rate, "-pass", "2", "-passlogfile", log,
"-c:a", "aac", "-b:a", f"{audio_kbps}k", ...], tmp, ...)
Even then the result can come out a few percent over. So the loop checks the real size and, if needed, retries at 0.92 × limit / size of the bitrate, up to four times.
The real numbers from the test run: a 60-second 1080p clip of 61.1 MB became 9.65 MB, 720p, H.264 at 1.18 Mbit/s plus 96 kbit/s AAC, in 32 seconds of encoding. Both passes report into the same progress arc: pass 1 fills the first 45%, pass 2 the rest.
That last detail was a bug in the first version. When a retry was needed, the second attempt reported progress from 0% again, so the arc filled up, dropped back to nothing and filled again. Now each retry only fills part of what's left of the bar, and a test asserts the progress values never go down.
Audio is the same idea with one number: the bitrate the length allows, capped at 320 kbit/s, retried if the encoder overshoots.
PDFs: the preset that made the file bigger
PDFs were where I learned the most, mostly about Ghostscript. The obvious approach is its -dPDFSETTINGS presets: /printer, /ebook and /screen, from heavy to light. I tried /screen on a scanned PDF and the output was bigger than the input.
The reason: scanners already store pages as JPEG. Ghostscript's presets downsample images above a threshold resolution, but by default they pass JPEG images through untouched, and then rewrite everything around them. On a scan that's almost all JPEG, you get the same images plus a slightly heavier wrapper.
So after the gentle presets, the ladder takes control of the images itself: turn off JPEG pass-through, force DCT (JPEG) encoding, set the resolution, and set the JPEG quality through QFactor, which isn't a command-line option at all. It has to be injected as PostScript before the input file:
for kind in ("Color", "Gray"):
args += [f"-dDownsample{kind}Images=true", f"-d{kind}ImageDownsampleType=/Bicubic",
f"-d{kind}ImageResolution={dpi}", f"-dAutoFilter{kind}Images=false",
f"-d{kind}ImageFilter=/DCTEncode"]
args.append("-dPassThroughJPEGImages=false")
dict_ = f"<< /QFactor {qfactor} /Blend 1 /HSamples [2 1 1 2] /VSamples [2 1 1 2] >>"
prologue = ["-c", f"<< /ColorImageDict {dict_} /GrayImageDict {dict_} >> setdistillerparams",
"-f"]
Each step of the ladder is tried in order until one fits. On the four-page scan (1.20 MB): the three presets all came out larger, then 150 dpi at QFactor 0.76 gave 0.558 MB, and the steps after that go down to 0.040 MB at 50 dpi, which is the "still readable, barely" end. A 600 KB limit stops at the first image step, at 150 dpi, which still reads comfortably on screen.
Testing size targets
These tests can't be "convert a small PNG and check it worked". They use worst cases on purpose: pure random noise for images (it barely compresses), a 720p video encoded at 6 Mbit/s, a 30-second noise track at 320 kbit/s, and a PDF full of noise pages. Each test asserts the result is at or under the limit, and the photo test also asserts it's above a floor, so "fits" can't quietly become "crushed":
out = convert(src, "fit-10mb", Options(fit_bytes=400_000))[0]
assert out.stat().st_size <= 400_000
assert out.stat().st_size > 250_000 # used most of the budget, not crushed
The command line got the same scrutiny. In the first version, dotmorph convert a.jpg --to webp --fit 1M converted to WebP and silently ignored the limit. Now --fit only works with the size tools, and says so:
dotmorph convert: --fit works with the size tools, not --to webp (drop --to, or use --to fit-10mb / fit-16mb / fit-25mb)
Try it
dotmorph convert clip.mp4 --fit 8M # any limit
dotmorph convert photos/*.jpg --to fit-10mb
dotmorph convert scan.pdf --to fit-25mb
Or right-click the file → DotMorph → Tools → ≤ 10 MB.
Part 7 is the last part about 2.2, and the most fun to build: seven UI sounds made from sine waves in pure Python, nine languages with real plural rules, and a screenshot for this series that caught a bug my tests had missed.
DotMorph is free and open source: github.com/kareem2099/DotMorph.



Top comments (0)