Image Compressor — Python source
Shrink image file sizes entirely in your browser — fixed quality or an automatic fit to a size budget, optional max-dimension resize, batch support. Nothing uploads.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""image-compressor — re-encode images smaller, at a fixed quality or to fit a size budget.
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `image-compressor` tool, ported from
src/tools/ImageCompressor.tsx.
The island's heavy lifting is canvas-bound (createImageBitmap -> drawImage ->
canvas.toBlob(mime, q)), so it stays in the browser. What ports is the
deterministic layer around it: the MIME-selection rule, the max-dimension
resize math, and the binary search for the largest quality whose encoded size
fits a byte budget. The encoder plugs in as a ``encode_size(q)`` callable —
the stand-in below is sized like a real one (Pillow's WebP ``quality=`` sits
behind the same signature).
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import math
from typing import Callable, Optional, Tuple
def output_mime(file_type: str) -> str:
"""PNG sources re-encode as WebP (lossy pipeline); JPEG/WebP keep theirs."""
return file_type if file_type in ("image/jpeg", "image/webp") else "image/webp"
def target_dimensions(width: int, height: int, max_dim: int) -> Tuple[int, int]:
"""Scale a source size down so no side exceeds ``max_dim``, never up.
``max_dim = 0`` keeps the original size. Each side is clamped at 1 px.
``floor(x + 0.5)`` reproduces JavaScript ``Math.round`` (half-up);
Python's built-in ``round`` is banker's rounding and would drift on
exact .5 values.
"""
scale = min(1.0, max_dim / max(width, height)) if max_dim > 0 else 1.0
return (
max(1, math.floor(width * scale + 0.5)),
max(1, math.floor(height * scale + 0.5)),
)
def compress_to_budget(
encode_size: Callable[[float], int], target_kb: int
) -> Optional[int]:
"""Binary-search the canvas quality (5..95) until the size fits the budget.
The budget is ``target_kb * 1024`` bytes — the core of the island's
target mode. Quality moves in whole points, ``mid = (lo + hi) // 2``, and
the loop runs at most seven times — enough to settle 5..95. Returns the
best fitting quality, or ``None`` when nothing fits (the island then
re-encodes once at the 5-point floor).
"""
budget = target_kb * 1024
lo, hi = 5, 95
best: Optional[int] = None
for _ in range(7):
if lo > hi:
break
mid = (lo + hi) // 2
if encode_size(mid / 100) <= budget:
best = mid # fits — try higher quality
lo = mid + 1
else:
hi = mid - 1 # too big — step down
return best
def _fake_encode_size(q: float) -> int:
"""Deterministic stand-in codec: size grows ~linearly with quality."""
return round(12000 + 88000 * q)
if __name__ == "__main__":
# The live tool decodes the bitmap, draws it to a canvas, then searches.
# 50 KB budget: a mid-range quality fits just under it.
quality = compress_to_budget(_fake_encode_size, 50)
if quality is None:
print("no quality fits — falling back to the 5-point floor")
else:
print(f"best quality {quality} -> {_fake_encode_size(quality / 100)} bytes")
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →