Pure-MoonBit image decoder/encoder covering BMP / QOI / TGA / PNG / GIF / JPEG / ICO / TIFF / FIM with zero external runtime dependencies. Decoders raise a structured `DecodeError` sub-error type so callers can branch on cause (UnsupportedFormat / TruncatedData / InvalidHeader / InvalidValue / EncodeNotImplemented). 0.3.7 re-licensed under MIT only (was `MIT OR Apache-2.0`); see LICENSE-MIT for the full text. 0.3.8 compiles against the current MoonBit core (the `try?` operator was removed upstream) and declares js / wasm-gc support in addition to native. 0.3.9 corrects the release note for 0.3.8; the code is unchanged. 0.3.10 fixes a crash in detect_format() on TGA files carrying a v2 footer and adds decode tests for the JPEG / PNG / GIF / TGA codecs. 0.3.11 adds from-scratch encoders for PNG / GIF / JPEG / TGA / ICO / TIFF (the DEFLATE, LZW and DCT code is written in this package, with no new dependency) and fixes three decoder bugs they exposed: the JPEG inverse DCT transposed every 8x8 block, the PNG inflater dropped the tail of the stream, and the ICO decoder read DIB-only entries at double height. 0.3.12 keeps the release CI's log files out of the published package; the codecs are unchanged. 0.3.13 is the result of a speed and quality comparison against the reference implementation: the TIFF decoder gains LZW / PackBits / Deflate, multiple strips and the horizontal predictor, the TIFF encoder writes compressed strips, the JPEG decoder gets the AAN inverse DCT and an eight-bit-at-a-time Huffman table (about six times faster), the GIF encoder stops writing corrupt files once the LZW table fills up, and the PNG inflater is rewritten. The quality is unchanged and no format is measurably worse than the reference. 0.3.14 hardens every decoder against malformed input: a u32 above 2^31 read into a signed Int32 became a negative offset that passed every bounds check, and the region checks and the allocation sizes themselves overflowed an Int32 on a corrupt header. The decoders now use a checked size helper, a 2^27-pixel cap and Int64 region checks, the JPEG decoder no longer trusts the contents of its segments, and the GIF colour tables and the JPEG marker loop are bounds-checked. PixelFormat and ImageFormat are pub(all), so their variants can be constructed by a consumer, and the package ships a native-only malformed-input regression test.
| # | Defect | Where |
|---|---|---|
| 1 | A u32 above 2³¹ read into a signed Int32 came back negative | utils.mbt |
| 2 | Bounds checks whose own arithmetic overflowed an Int32 | bmp.mbt, tga.mbt, ico.mbt, tiff.mbt, png.mbt |
| 3 | Allocation sizes computed from file-derived dimensions overflowed | bmp.mbt, tga.mbt, qoi.mbt, png.mbt, tiff.mbt, fim.mbt |
| 4 | Reads with no bounds check at all | the GIF colour tables, the JPEG marker loop |
| 5 | An unchecked write destination in the BMP RLE decoders | bmp.mbt |
| 6 | The JPEG decoder trusted the contents of each segment | jpeg.mbt |
| Format | Entry point | What it writes |
|---|---|---|
| PNG | encode_png | 8-bit Gray / Gray+Alpha / RGB / RGBA, colour type taken from the pixel format, five row filters chosen by the minimal-absolute-sum heuristic, hand-written DEFLATE (fixed Huffman + LZ77 with a 32 KiB window) |
| GIF | encode_gif | GIF89a, one frame, global colour table, binary transparency, LZW; exact palette when the image has few enough colours, median-cut quantisation otherwise |
| JPEG | encode_jpeg(image, quality) | baseline sequential (SOF0), JFIF APP0, 4:4:4 (no chroma subsampling), Annex K quantisation and Huffman tables, 8-point forward DCT; JPEG has no alpha channel, so alpha is dropped |
| TGA | encode_tga / encode_tga_rle | types 2 / 3 (uncompressed) and types 10 / 11 (run-length encoded), 24-bit BGR or 32-bit BGRA |
| ICO | encode_ico | ICONDIR + one 16-byte directory entry + a DIB-only payload (BITMAPINFOHEADER, bottom-up BGRA XOR bitmap, 1-bpp AND mask padded to 4 bytes) |
| TIFF | encode_tiff | little-endian (II), LZW-compressed strips with the horizontal differencing predictor; 1 sample for gray, 3 for RGB, 4 for RGBA (ExtraSamples = 2) |
| Field | Supported |
|---|---|
| Byte order | II (little-endian); MM raises InvalidHeader |
| Compression | 1 (none), 5 (LZW), 8 / 32946 (Deflate), 32773 (PackBits) |
| Predictor | 1 (none), 2 (horizontal differencing) |
| Photometric | 0 (WhiteIsZero), 1 (BlackIsZero), 2 (RGB), 3 (Palette) |
| BitsPerSample | 1 / 2 / 4 / 8 / 16 (uniform across samples) |
| SamplesPerPixel | 1 (greyscale / palette), 3 (RGB) or 4 (RGBA) |
| PlanarConfiguration | 1 (chunky); planar rejected |
| Layout | one or more strips; every strip is decompressed on its own |
| Sample format | UINT |
| Variant | When it fires |
|---|---|
| DecodeError::UnsupportedFormat(String) | magic bytes do not match any known format signature |
| DecodeError::TruncatedData(String) | reserved — no codec raises it yet |
| DecodeError::InvalidHeader(String) | a header field is out of range or has an unsupported value; this is what every codec-level Failure is wrapped as |
| DecodeError::InvalidValue(String) | reserved — no codec raises it yet |
| DecodeError::EncodeNotImplemented(String) | encode() was called with a decode-only format |
match fmt {
ImageFormat::BMP => ...
f if f.is_decodable() => ...
}// format sniffing; None when the magic bytes match nothing
pub fn detect_format(data : Bytes) -> ImageFormat?
// one-shot auto-detect decoder; raises DecodeError
pub fn decode(data : Bytes) -> Image raise DecodeError
// decode a file whose format is already known; skips the sniffing step
pub fn decode_by_format(data : Bytes, format : ImageFormat) -> Image raise DecodeError
// header-only dimension read (no pixel decode)
pub fn image_dimensions(data : Bytes) -> (Int32, Int32, ImageFormat) raise DecodeError
// per-format decoders (still raise the lower-level Failure)
pub fn decode_bmp(data : Bytes) -> Image raise Failure
pub fn decode_qoi(data : Bytes) -> Image raise Failure
pub fn decode_tga(data : Bytes) -> Image raise Failure
pub fn decode_png(data : Bytes) -> Image raise Failure
pub fn decode_gif(data : Bytes) -> Image raise Failure
pub fn decode_jpeg(data : Bytes) -> Image raise Failure
pub fn decode_ico(data : Bytes) -> Image raise Failure
pub fn decode_tiff(data : Bytes) -> Image raise Failure
pub fn decode_fim(data : Bytes) -> Image raise Failure // dual-energy side-by-side, Gray8
pub fn decode_fim_raw(data : Bytes) -> Image raise Failure // raw 16-bit detector, GrayA8
pub fn fim_dimensions(data : Bytes) -> (Int32, Int32) raise Failure // raw detector (width, height)
// the GIF animation path: every frame, composited onto the logical screen
pub fn decode_gif_all(data : Bytes) -> AnimatedImage raise Failure
// FIM geometry helpers (GrayA8 in, GrayA8 out)
pub fn fim_side_by_side(left : Image, right : Image) -> Image raise Failure
pub fn fim_split_rows(img : Image) -> (Image, Image) raise Failure
pub fn fim_split_cols(img : Image) -> (Image, Image) raise Failure
pub fn fim_apply_y_roll(img : Image, shift_px : Int32) -> Image raise Failure
pub fn fim_find_bright_strip(img : Image, air_threshold? : Double = 50000.0) -> (Int32, Int32) raise Failure
pub fn fim_find_auto_y_roll(img : Image) -> Int32 raise Failure
// FIM renderers
pub fn fim_to_grayscale8(img : Image, invert? : Bool = true, degamma? : Bool = false,
percentile_low? : Double? = Some(1.0),
percentile_high? : Double? = Some(99.0)) -> Image raise Failure
pub fn fim_ratio_grayscale(low : Image, high : Image) -> Image raise Failure
pub fn fim_ratio_pseudo_color(low : Image, high : Image) -> Image raise Failure
pub fn fim_ratio_pseudo_color_hsb(low : Image, high : Image) -> Image raise Failure
// writers (QOI, BMP, PNG, GIF, JPEG, TGA, ICO, TIFF); encode() raises
// DecodeError::EncodeNotImplemented for FIM only
pub fn encode(image : Image, format : ImageFormat) -> Bytes raise DecodeError
pub fn encode_qoi(image : Image) -> Bytes raise Failure
pub fn encode_bmp(image : Image) -> Bytes raise Failure
pub fn encode_png(image : Image) -> Bytes raise Failure
pub fn encode_gif(image : Image) -> Bytes raise Failure
pub fn encode_jpeg(image : Image, quality : Int32) -> Bytes raise Failure
pub fn encode_tga(image : Image) -> Bytes raise Failure
pub fn encode_tga_rle(image : Image) -> Bytes raise Failure
pub fn encode_ico(image : Image) -> Bytes raise Failure
pub fn encode_tiff(image : Image) -> Bytes raise Failure// decode a JPEG -> Image, resize, re-encode as QOI
///|
let img = @moonbit_image.decode(jpeg_bytes) catch {
err => {
@log.warn("decode failed: \{err}")
abort("give up")
}
}
///|
let half = img.resize_nearest(img.width / 2, img.height / 2)
///|
let qoi = @moonbit_image.encode(half, @moonbit_image.ImageFormat::QOI)pub suberror DecodeError {
UnsupportedFormat(String)
TruncatedData(String)
InvalidHeader(String)
InvalidValue(String)
EncodeNotImplemented(String)
}fn AnimatedImage::new(frames : Array[Image], delays : Array[Int], width : Int, height : Int, loop_count : Int) -> AnimatedImagepub struct Color {
r : Int
g : Int
b : Int
a : Int
}pub(all) enum ImageFormat {
BMP
QOI
TGA
PNG
GIF
JPEG
ICO
TIFF
FIM
}pub(all) enum PixelFormat {
Gray8
GrayA8
RGB8
RGBA8
}fn deflate_compress(data : Bytes) -> Bytesfn zlib_compress(data : Bytes) -> BytesInstall
Download zipPure-MoonBit image decoder/encoder covering BMP / QOI / TGA / PNG / GIF / JPEG / ICO / TIFF / FIM with zero external runtime dependencies. Decoders raise a structured `DecodeError` sub-error type so callers can branch on cause (UnsupportedFormat / TruncatedData / InvalidHeader / InvalidValue / EncodeNotImplemented). 0.3.7 re-licensed under MIT only (was `MIT OR Apache-2.0`); see LICENSE-MIT for the full text. 0.3.8 compiles against the current MoonBit core (the `try?` operator was removed upstream) and declares js / wasm-gc support in addition to native. 0.3.9 corrects the release note for 0.3.8; the code is unchanged. 0.3.10 fixes a crash in detect_format() on TGA files carrying a v2 footer and adds decode tests for the JPEG / PNG / GIF / TGA codecs. 0.3.11 adds from-scratch encoders for PNG / GIF / JPEG / TGA / ICO / TIFF (the DEFLATE, LZW and DCT code is written in this package, with no new dependency) and fixes three decoder bugs they exposed: the JPEG inverse DCT transposed every 8x8 block, the PNG inflater dropped the tail of the stream, and the ICO decoder read DIB-only entries at double height. 0.3.12 keeps the release CI's log files out of the published package; the codecs are unchanged. 0.3.13 is the result of a speed and quality comparison against the reference implementation: the TIFF decoder gains LZW / PackBits / Deflate, multiple strips and the horizontal predictor, the TIFF encoder writes compressed strips, the JPEG decoder gets the AAN inverse DCT and an eight-bit-at-a-time Huffman table (about six times faster), the GIF encoder stops writing corrupt files once the LZW table fills up, and the PNG inflater is rewritten. The quality is unchanged and no format is measurably worse than the reference. 0.3.14 hardens every decoder against malformed input: a u32 above 2^31 read into a signed Int32 became a negative offset that passed every bounds check, and the region checks and the allocation sizes themselves overflowed an Int32 on a corrupt header. The decoders now use a checked size helper, a 2^27-pixel cap and Int64 region checks, the JPEG decoder no longer trusts the contents of its segments, and the GIF colour tables and the JPEG marker loop are bounds-checked. PixelFormat and ImageFormat are pub(all), so their variants can be constructed by a consumer, and the package ships a native-only malformed-input regression test.