Image Converter — Python source
Convert images between PNG, JPEG and WebP entirely in your browser. Batch-friendly with quality control and a before/after size delta — nothing is uploaded.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""image-converter — convert image bytes between PNG, JPEG, and WebP.
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `image-converter` tool, ported from
src/tools/ImageConverter.tsx.
Decoding/encoding run through browser codecs (createImageBitmap /
canvas.toBlob) with no Python stdlib equivalent, so this port keeps the
tool's deterministic core: the format tables, output naming, quality
mapping, the ±size-delta badge, and the alpha flatten a JPEG needs on raw
RGBA bytes.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import re
# Target formats in SegmentedControl order; the tool defaults to WebP.
TARGETS = ("png", "jpeg", "webp")
DEFAULT_TARGET = "webp"
# The tool's MIME map — canvas.toBlob's container-format argument.
MIME = {"png": "image/png", "jpeg": "image/jpeg", "webp": "image/webp"}
# The tool's EXT map — download suffixes; JPEG saves as .jpg.
EXT = {"png": "png", "jpeg": "jpg", "webp": "webp"}
# Quality slider range and default (PNG ignores the knob; it is lossless).
QUALITY_MIN, QUALITY_MAX, DEFAULT_QUALITY = 10, 100, 85
def resolve_target(value: str) -> str:
"""Snap an unknown target back to the tool's default (WebP)."""
return value if value in TARGETS else DEFAULT_TARGET
def mime_type(target: str) -> str:
"""The ``image/<target>`` string canvas.toBlob receives."""
return MIME[resolve_target(target)]
def output_name(name: str, target: str = DEFAULT_TARGET) -> str:
"""Strip the old extension (``re.sub(r"\\.[^.]+$", ...)``) and re-suffix."""
return re.sub(r"\.[^.]+$", "", name) + "." + EXT[resolve_target(target)]
def encoder_quality(quality: int = DEFAULT_QUALITY) -> float:
"""Slider units (10..100) -> the 0..1 quality argument codecs take."""
q = min(QUALITY_MAX, max(QUALITY_MIN, round(quality)))
return q / 100
def is_image_type(media_type: str) -> bool:
"""DropZone filter: only ``image/*`` files enter the batch."""
return media_type.startswith("image/")
def size_delta_percent(original_size: int, converted_size: int) -> float:
"""The ±NN% badge shown under each converted thumbnail."""
return (converted_size - original_size) / original_size * 100
def format_size_delta(delta_percent: float) -> str:
"""Shrinkage renders with U+2212 minus (green in the UI), growth a plus."""
sign = "−" if delta_percent <= 0 else "+"
return f"{sign}{abs(round(delta_percent))}%"
def flatten_onto_white(rgba: bytearray) -> None:
"""Flatten alpha in place over opaque white (RGBA8, tightly packed).
JPEG has no alpha channel; the browser does this by painting #fff onto
the canvas and then drawing the image — source-over compositing, rounded
per channel: ``out = (src * a + 255 * (255 - a) + 127) // 255`` — the
same formula the C/C++/Zig twins of this tool use.
"""
for i in range(0, len(rgba), 4):
a = rgba[i + 3]
for c in range(3):
rgba[i + c] = (rgba[i + c] * a + 255 * (255 - a) + 127) // 255
rgba[i + 3] = 255
if __name__ == "__main__":
# Two-pixel demo: half-transparent red + fully transparent blue.
pixels = bytearray([255, 0, 0, 128, 0, 128, 255, 0])
flatten_onto_white(pixels)
print(mime_type("jpeg"), output_name("photo.png", "jpeg"), encoder_quality(85))
print(format_size_delta(size_delta_percent(2000, 1500)), pixels.hex())
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 →