Image Converter — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package imageconverter ports CosmoDev's `image-converter` tool (the web
// island is src/tools/ImageConverter.tsx). Go's standard library ships real
// codecs — PNG/JPEG/GIF decode, PNG/JPEG encode — so this twin runs the
// tool's actual pipeline: decode -> (JPEG only) flatten alpha onto white ->
// re-encode at quality. WebP has no stdlib codec and errors out, the one
// divergence from the browser's canvas.toBlob.
//
// Language: Go (standard library only).
// CosmoDev polyglot showcase port of the `image-converter` tool, ported from
// src/tools/ImageConverter.tsx.
//
// display source — part of CosmoDev's polyglot tool pages.
package imageconverter
import (
"bytes"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
_ "image/gif" // register the GIF decoder; the browser accepts GIFs too
"image/jpeg"
"image/png"
"math"
"path"
"strings"
)
// Format is a target container, in the tool's SegmentedControl order
// (default WebP). Quality slider: 10..100, default 85; PNG ignores the knob.
type Format string
const (
Png Format = "png"
Jpeg Format = "jpeg"
Webp Format = "webp"
DefaultFormat Format = Webp
DefaultQuality = 85
QualityMin = 10
QualityMax = 100
)
// The tool's MIME map (canvas.toBlob's container format) and EXT map
// (download suffixes; JPEG saves as .jpg).
var mime = map[Format]string{Png: "image/png", Jpeg: "image/jpeg", Webp: "image/webp"}
var ext = map[Format]string{Png: "png", Jpeg: "jpg", Webp: "webp"}
// resolve snaps an unknown target back to the tool's default (WebP).
func resolve(f Format) Format {
if f == Png || f == Jpeg || f == Webp {
return f
}
return DefaultFormat
}
// MimeType returns the `image/<format>` string handed to canvas.toBlob.
func MimeType(f Format) string { return mime[resolve(f)] }
// OutputName mirrors the tool's outName helper (JS: stripping /\.[^.]+$/ —
// at least one char must follow the dot) and appends the target's extension.
func OutputName(name string, f Format) string {
stem := name
if e := path.Ext(name); len(e) > 1 {
stem = strings.TrimSuffix(name, e)
}
return stem + "." + ext[resolve(f)]
}
// EncoderQuality clamps the slider value (10..100) into the JPEG encoder's
// 1..100 range; the web tool divides by 100 for canvas.toBlob's 0..1 scale.
func EncoderQuality(quality int) int {
return min(QualityMax, max(QualityMin, quality)) // Go 1.21 builtins
}
// IsImageType mirrors the DropZone filter: only `image/*` files are batched.
func IsImageType(mediaType string) bool {
return strings.HasPrefix(mediaType, "image/")
}
// SizeDeltaPercent is the ±NN% badge under each converted thumbnail;
// FormatSizeDelta renders it (U+2212 minus = shrinkage, green in the UI).
func SizeDeltaPercent(original, converted int) float64 {
return float64(converted-original) / float64(original) * 100
}
func FormatSizeDelta(deltaPercent float64) string {
sign := "+"
if deltaPercent <= 0 {
sign = "−"
}
return fmt.Sprintf("%s%.0f%%", sign, math.Abs(deltaPercent))
}
// flattenOntoWhite composites src over opaque white — the source-over result
// of painting #fff then drawImage'ing the bitmap; without it JPEG renders
// transparency black.
func flattenOntoWhite(src image.Image) *image.RGBA {
b := src.Bounds()
canvas := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(canvas, canvas.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
draw.Draw(canvas, canvas.Bounds(), src, b.Min, draw.Over)
return canvas
}
// Convert decodes input and re-encodes it as the target format (quality
// 10..100; PNG ignores it). WebP errors: no stdlib encoder.
func Convert(input []byte, f Format, quality int) ([]byte, error) {
f = resolve(f)
if f == Webp {
return nil, errors.New("webp encoding is not in the Go standard library")
}
src, _, err := image.Decode(bytes.NewReader(input))
if err != nil {
return nil, err
}
var buf bytes.Buffer
if f == Jpeg {
err = jpeg.Encode(&buf, flattenOntoWhite(src), &jpeg.Options{Quality: EncoderQuality(quality)})
} else {
err = png.Encode(&buf, src)
}
return buf.Bytes(), err
}
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 →