pixelforge

    Pure MoonBit image processing library with filters, morphology, bilateral and color-space operations, affine transforms, drawing primitives with a bitmap font, layer compositing with blend modes, PNG/GIF/QOI/BMP codecs, baseline TIFF decoding, and JPEG/WebP/AVIF codec adapters. Backend-agnostic (js, wasm-gc, native) with a browser Playground.

    image
    image-processing
    filters
    convolution
    wasm
    canvas
    Download zip
    Author
    Version
    0.17.5
    License
    Apache-2.0
    Last updated
    2 months ago
    Downloads
    229

    #PixelForge

    CI

    English | 简体中文

    一个纯 MoonBit 实现的图像处理库,附带一个在浏览器里实时运行的 Playground。 后端无关的核心库可编译到 JavaScript / WebAssembly (wasm-gc & 线性内存 wasm) / native。

    稳定 API 里程碑已发布:GitHub 保留 v1.0.0 作为稳定版标记;当前 MoonBit 包版本为 0.14.0(mooncakes.io 要求主版本号为 0)。公开 API 在 0.x 系列中保持兼容,破坏性变更会记录在 CHANGELOG。

    PixelForge 浏览器 Playground

    同一界面一键切换 20+ 种滤镜与 JS / WebAssembly 双引擎——以 Sobel 边缘检测为例:

    Sobel 边缘检测


    #✨ 特性

    • 丰富的滤镜与几何变换:灰度、反色、亮度、对比度、高斯/盒式模糊、锐化、浮雕、拉普拉斯/Sobel/Scharr/Canny 边缘、棕褐色、二值化、像素化、中值降噪、直方图均衡、色调分离、伽马校正、暗角、饱和度、色相旋转、水平/垂直翻转;另有 90° 旋转与最近邻/双线性/双三次 (Catmull-Rom) 缩放。
    • 形态学运算:3×3 腐蚀 / 膨胀 / 开运算 / 闭运算。
    • 纹理描述:lbp_codes() / lbp_histogram() 提供 8 邻域局部二值模式特征。
    • 高级特征:harris_corners() 提供确定性的 Harris 角点检测与非极大值抑制。
    • 高级特征:hog() 提供可配置 cell/block 的方向梯度直方图,contours() 提取阈值连通域边界像素,skeletonize() 使用有界 Zhang–Suen 细化生成骨架。
    • 流式遍历:for_each_tile() / for_each_row() 提供不复制像素缓冲的分块与逐行访问;需要独立图像时再调用 tile 的 copy()。
    • 图像编解码:PNG(支持 8-bit 灰度、灰度透明、调色板、RGB/RGBA 与 tRNS;自实现完整 DEFLATE inflate,编码端使用自适应行过滤和 fixed-Huffman 压缩,并校验 CRC-32/Adler-32)、GIF 编码/解码(单帧 GIF89a 编码、变长 LZW、交错、透明索引)、QOI、BMP 与 TIFF(多条带、分块、PackBits/LZW/Deflate、Predictor=2、有限 BigTIFF)解码;JPEG 编解码、无损 WebP 编码和 JS 目标 AVIF 编码通过 mizchi/image 适配。
    • GIF 动画帧:gif_decode_all() 返回每帧图像、位置、延迟、透明索引和 disposal 元数据;gif_decode() 继续提供首帧便捷 API。Playground 上传 GIF 时保留浏览器动画预览,编辑管线仍以首帧作为像素输入。
    • 格式探测:detect_image_format() 与 image_metadata() 可在不解码像素的情况下识别 PNG/GIF/QOI/BMP/JPEG/WebP/AVIF/TIFF,并读取常见容器的尺寸与 GIF 动画标记。
    • 仿射变换:Affine 矩阵(旋转/平移/缩放/错切 + 复合 + 求逆),逆映射双线性采样;任意角度 rotate(degrees)。
    • 绘图原语:Bresenham 直线、矩形、中点圆、填充,全部自动边界裁剪。
    • 可分离高斯模糊:gaussian(radius) 任意半径,二项式权重行列分离,每像素 O(r) 而非 O(r²)。
    • 锐化蒙版:unsharp_mask(radius, amount) 复用高斯模糊提取高频细节并回叠,锐化边缘。
    • 裁剪与填充:crop(x, y, w, h)(自动限幅)与 pad(l, t, r, b, color)(颜色边框),crop∘pad 可无损往返。
    • 双边滤波:bilateral(radius, σs, σr) 保边平滑——平坦区域降噪,强边缘保持锐利。
    • 图像分析:Otsu 自动阈值(类间方差最大化)、Floyd–Steinberg 误差扩散抖动、四连通连通域标记与计数、chamfer (3,4) 距离变换、感知哈希(aHash/dHash + 汉明距离)。
    • 积分图与 O(1) 盒式模糊:integral_image() 求和面积表(Int64 防溢出)驱动 box_blur(radius),任意半径每像素 O(1)。
    • 泛洪填充:flood_fill(x, y, color, tolerance) 四连通种子填充,逐通道容差。
    • 图层合成:composite(top, mode) Porter-Duff source-over + 8 种混合模式(正片叠底/滤色/叠加/变暗/变亮/差值/线性减淡等),纯整数舍入运算。
    • 位图文字:内置 5×7 字体(数字/大写字母/基本标点),draw_text 整数倍缩放、自动裁剪。
    • 色彩空间:RGB ↔ HSV、RGB ↔ HSL(含 adjust_lightness)、RGB ↔ YCbCr (BT.601) 精确往返转换。
    • 直方图:histogram_luma() / histogram_rgb() 256 桶统计;Playground 内置实时亮度直方图面板。
    • 通用卷积引擎:Kernel + Image::convolve,可自定义任意奇数尺寸卷积核。
    • 图像统计与色调:stats() 逐通道 min/max/mean(Int64 累加)、auto_contrast() 自动对比度拉伸、levels(black, white, gamma) 色阶重映射。
    • 确定性噪声:add_gaussian_noise(seed, σ) / add_salt_pepper(seed, density),64 位 LCG 驱动,同 seed 跨后端逐字节一致。
    • 图像质量指标:mse() / psnr() 比较 RGBA 四通道;luma_mse() / ssim() 使用 Rec.601 亮度并忽略 alpha。
    • 局部阈值与区域统计:sauvola() / adaptive_mean() 使用积分图处理局部窗口;regionprops() 返回连通域面积、边界框和质心。
    • 纯整数、确定性:滤镜数学尽量用整数(如亮度权重 ×1000),结果可复现;测试覆盖正常、边界和畸形输入(含 CRC-32/Adler-32 公开参考向量与手工汇编的 DEFLATE 位流)。
    • 核心库零第三方依赖:图像处理包只使用 moonbitlang/core;native CLI 的文件模式单独使用官方 moonbitlang/x/fs。
    • 多后端 + 零拷贝互操作:js 后端下 FixedArray[Byte] 就是 Uint8Array,与 canvas 的 Uint8ClampedArray 零拷贝互通;线性内存 wasm 后端导出 memory,宿主直接批量读写像素。
    • 浏览器 Playground:拖拽 / 粘贴 / 上传图片,GIF 保持动画预览,滤镜可叠加成管线,JS/WASM 引擎切换与性能对比,可切换到 Web Worker 后台线程处理大图不卡 UI,处理结果用自家 png_encode 一键下载 PNG。

    #🆚 与 MoonBit 生态中其他图像库的关系

    MoonBit 生态中已经存在若干方向相近的图像处理包(如 megemini/millow、PingGuoMiaoMiao/MoonVision、shunge/image 等)。PixelForge 与它们在基础滤镜上不可避免地有重叠(模糊、边缘检测、阈值等是所有图像库的共同基础能力,且本库的实现全部独立手写、以确定性测试驱动),但定位与核心能力有明显差异:

    现有项目定位与 PixelForge 的差异
    megemini/millow更广的计算机视觉算法库(增强、轮廓/区域特征、HOG/LBP、SSIM 等)侧重 CV 算法;PixelForge 侧重零依赖、多后端编解码和浏览器交互
    PingGuoMiaoMiao/MoonVision轻量图像处理 + 基础 CV(灰度图为主、模板匹配)侧重灰度图像处理;不提供 RGBA 全彩编解码、绘图/文字、噪声与哈希
    shunge/image纯解码器(BMP/QOI/TGA/PNG/GIF/JPEG 六格式解码)仅解码;不提供滤镜、编码、绘图与分析能力

    PixelForge 当前重点打磨的能力:

    • 编解码器广度:PNG(自实现完整 DEFLATE inflate + CRC-32/Adler-32 校验)、QOI、BMP 的编+解与 GIF 解码,全部纯 MoonBit 实现
    • 浏览器 Playground:JS/WASM 双引擎实时对比、Web Worker 后台线程、实时亮度直方图面板、用自家 png_encode 下载结果
    • 位图字体:内置 5×7 字体 draw_text,可直接在图像上排版文字
    • 感知哈希:aHash / dHash + 汉明距离,图像去重与相似度检索
    • 确定性噪声:64 位 LCG 驱动的高斯 / 椒盐噪声,同 seed 跨后端逐字节重现,配合中值/双边滤波形成降噪演示闭环
    • 图像统计与色调:逐通道 min/max/mean、auto_contrast、levels 色阶
    • 工程透明度:13 个版本的完整演进记录、双语文档、CI 端到端冒烟测试

    如果您的项目在 mooncakes.io 上看到本库,可通过 moon add 0717lee/pixelforge 直接使用;也希望本库的编解码器与 Playground 实现能为生态提供参考。

    #📦 项目结构

    pixelforge/ ├── image.mbt # Image 数据结构、像素读写、clamp_byte ├── filters_basic.mbt # map_rgb 引擎 + 灰度/反色/亮度/对比度 ├── convolution.mbt # Kernel + convolve + 模糊/锐化/浮雕/边缘/Sobel/Scharr ├── filters_advanced.mbt # 棕褐色/二值化/像素化/中值/直方图均衡/色调分离 ├── filters_effects.mbt # 伽马校正/暗角 ├── colorspace.mbt # RGB↔HSV、RGB↔YCbCr、饱和度/色相旋转 ├── morphology.mbt # 3×3 腐蚀/膨胀/开/闭运算 ├── canny.mbt # Canny 边缘检测(NMS + 滞后阈值) ├── affine.mbt # 仿射变换(旋转/平移/缩放/错切,逆映射采样) ├── drawing.mbt # 绘图原语(Bresenham 直线/矩形/圆/填充) ├── gaussian.mbt # 可分离高斯模糊(任意半径,二项式权重) ├── unsharp.mbt # 锐化蒙版(复用高斯) ├── croppad.mbt # 裁剪 / 颜色边框填充 ├── integral.mbt # 积分图(SAT)+ O(1) 盒式模糊 ├── floodfill.mbt # 泛洪填充(四连通种子填充) ├── distance.mbt # chamfer (3,4) 距离变换 ├── stats.mbt # 图像统计 / 自动对比度 / 色阶 ├── bicubic.mbt # 双三次缩放(Catmull-Rom) ├── phash.mbt # 感知哈希(aHash/dHash + 汉明距离) ├── noise.mbt # 确定性噪声(高斯 / 椒盐,LCG) ├── hsl.mbt # HSL 色彩空间 + 亮度调整 ├── histogram.mbt # 直方图 API(亮度 / RGB) ├── bilateral.mbt # 双边滤波(保边平滑) ├── otsu.mbt # Otsu 自动阈值(类间方差最大化) ├── dither.mbt # Floyd–Steinberg 误差扩散抖动 ├── components.mbt # 四连通连通域标记/计数 ├── blend.mbt # 图层合成(source-over + 8 种混合模式) ├── text.mbt # 5×7 位图字体 draw_char/draw_text ├── png.mbt # PNG 编解码(完整 DEFLATE inflate + 校验) ├── gif.mbt # GIF 解码(变长 LZW、交错、透明索引) ├── qoi.mbt # QOI 图像编解码(完整规范) ├── bmp.mbt # BMP 编解码(无压缩 24/32 位) ├── transform.mbt # 水平/垂直翻转、90° 旋转 ├── resize.mbt # 最近邻/双线性缩放 ├── dispatch.mbt # Image::apply_filter_id 统一派发(各绑定共用) ├── pipeline.mbt # 类型安全、可复用的 Filter / Pipeline 管线 API ├── metrics.mbt # MSE / PSNR / luma MSE / SSIM ├── adaptive_threshold.mbt # Sauvola / 局部均值阈值 ├── regionprops.mbt # 连通域面积、边界框、质心 ├── *_test.mbt # 确定性测试(黑盒 + 白盒) ├── cmd/main/ # 原生 CLI 示例(moon run cmd/main) ├── cmd/ppm/ # PPM 图像输出示例(moon run cmd/ppm > edges.ppm) ├── cmd/showcase/ # 综合展示(绘图+文字+滤镜+PNG 往返自检) ├── cmd/cli/ # native info/convert 编解码 CLI + 十六进制模式 ├── web/ # 浏览器绑定 + Playground(HTML/CSS/JS) │ ├── bindings.mbt # js 后端绑定 apply_filter(零拷贝) │ ├── dist/web.js # 已构建的 MoonBit→JS 产物 │ ├── dist/wasmcore.wasm # 已构建的线性内存 wasm 产物 │ └── index.html / playground.js / style.css ├── wasmcore/ # 线性内存 wasm 绑定(alloc/process + 导出 memory) ├── scripts/build-web.mjs # 构建并校验 web/dist 产物 └── serve.mjs # 零依赖静态服务器

    #🚀 快速开始

    先安装 MoonBit 工具链。

    moon test # 运行完整单元测试套件 moon run cmd/main # 运行原生示例(生成图像并跑滤镜,打印校验和) moon run cmd/showcase > showcase.ppm # 综合展示:绘图+文字+滤镜+PNG 往返自检 moon run cmd/ppm > edges.ppm # 生成一张 Sobel 边缘检测的 PPM 图片 moon run --target native cmd/cli -- --help # 查看文件编解码 CLI

    启动浏览器 Playground(web/dist/ 中已包含构建好的产物):

    node serve.mjs # 然后打开 http://localhost:8123

    Playground 默认把上传图片缩放到最长边 1024 像素作为预览,以避免浏览器在连续渲染时占用过多内存;页面会显示实际预览尺寸,下载结果也使用该尺寸。需要处理原始分辨率时,请直接调用库 API 或在宿主中自行设置像素上限。

    如需从源码重新构建 Web 产物:

    node scripts/build-web.mjs # 构建并同步 web/dist/ node scripts/build-web.mjs --check # 仅检查提交的产物是否同步

    #🧑‍💻 库用法

    // 从 RGBA 字节缓冲区(w*h*4)构造图像
    let img = @pixelforge.Image::from_bytes(width, height, rgba_bytes)

    // 链式调用滤镜(每个滤镜返回一张新图,不修改原图)
    let stylized = img.grayscale().sobel()
    let soft = img.blur().brightness(20)

    // 自定义卷积核
    let kernel = @pixelforge.Kernel::new(3, [0.0, -1.0, 0.0, -1.0, 5.0, -1.0, 0.0, -1.0, 0.0], 1.0, 0.0)
    let sharp = img.convolve(kernel)

    // 按数字 id 派发(供各宿主绑定 / CLI 共用)
    let out = img.apply_filter_id(8, 0.0) // 8 = Sobel

    // 类型安全的可复用管线(按追加顺序执行)
    let pipeline = @pixelforge.Pipeline::new()
    .append(@pixelforge.Filter::Grayscale)
    .append(@pixelforge.Filter::Contrast(1.25))
    .append(@pixelforge.Filter::Sobel)
    let out2 = img.apply_pipeline(pipeline)

    // 质量指标:RGBA 误差与 Rec.601 亮度相似度
    let error = img.mse(out2)
    let score = img.psnr(out2)
    let similarity = img.ssim(out2)

    // 取回处理后的像素
    let bytes = out.data // FixedArray[Byte],长度 = width*height*4

    mse/psnr 比较 RGBA 四通道;luma_mse/ssim 使用 Rec.601 luma 并忽略 alpha。ssim 使用覆盖整张图的单个 population-statistics 窗口(无滑动窗口补边),相同尺寸的空图返回 1;比较尺寸不一致会拒绝。

    #错误与边界

    • png_decode、gif_decode、qoi_decode、bmp_decode、tiff_decode 对格式错误或不支持的输入返回 None;核心包没有纯 MoonBit 的 WebP/AVIF 解码器,浏览器 Playground 通过 web/codecs.js 调用原生 WebP/AVIF 解码。
    • Image::new、Image::from_bytes 以及尺寸必须一致的合成操作会拒绝非法尺寸或缓冲区;坐标 API 要求调用方传入图像范围内的坐标。
    • 编解码器和构造器都会限制图像尺寸,宿主在接收不可信图片时仍应设置更严格的文件大小和像素上限。
    • Playground 主要演示常用滤镜和双后端切换;完整的编解码、几何、绘图、分析和合成 API 通过 MoonBit 库直接使用。

    #🎛️ 滤镜清单

    id滤镜方法amount
    0灰度grayscale()—
    1反色invert()—
    2亮度brightness(delta)−255..255
    3对比度contrast(factor)0.0..3.0
    4高斯模糊blur()—
    5锐化sharpen()—
    6浮雕emboss()—
    7拉普拉斯边缘edges()—
    8Sobel 边缘sobel()—
    9棕褐色sepia()—
    10二值化threshold(level)阈值(默认 128)
    11像素化pixelate(block)块大小(默认 8)
    12中值降噪median()—
    13直方图均衡histogram_equalize()—
    14水平翻转flip_horizontal()—
    15垂直翻转flip_vertical()—
    16色调分离posterize(levels)色阶数(默认 4)
    17伽马校正gamma(value)伽马值(默认 2.2)
    18暗角vignette(strength)强度 0..1(默认 0.5)
    19Scharr 边缘scharr()—
    20Canny 边缘canny(low, high)高阈值(默认 100,低阈值取一半)
    21Otsu 自动阈值otsu()—
    22Floyd–Steinberg 抖动(二值)dither_mono()—

    会改变尺寸的变换不走 id 派发,直接调用库 API:rotate90()、resize_nearest(w, h)、resize_bilinear(w, h)、resize_bicubic(w, h)。多参数 / 非图像→图像的 API 同理:average_hash()/difference_hash()/hamming_distance、add_gaussian_noise/add_salt_pepper、histogram_luma()/histogram_rgb()、rgb_to_hsl/hsl_to_rgb/adjust_lightness、box_blur(radius)、flood_fill(x, y, color, tol)、distance_transform(t)、gaussian(radius)、unsharp_mask(radius, amount)、crop(x, y, w, h)、pad(l, t, r, b, color)、bilateral(radius, σs, σr)、dither_grayscale(levels)/dither_mono()、otsu_threshold()、label_components(t)/count_components(t)、composite(top, mode)、draw_text(...)、rotate(deg)、translate(dx, dy)、affine(t)、draw_line/draw_rect/draw_circle 等绘图原语、saturate(factor)、hue_rotate(deg)、erode()/dilate()/morph_open()/morph_close()、png_encode/png_decode、gif_encode/gif_decode、qoi_encode/qoi_decode、bmp_encode/bmp_decode、tiff_decode、jpeg_decode/jpeg_encode、webp_encode、avif_encode、rgb_to_hsv 等色彩空间函数。

    #🏗️ 架构与多后端

    核心库完全后端无关。两个宿主绑定包分别演示两种进出 MoonBit 的方式:

    • web/(js 后端):MoonBit 的 FixedArray[Byte] 编译为 JS Uint8Array,因此 canvas 的 ImageData.data(Uint8ClampedArray)可以零拷贝直接传入 apply_filter。
    • wasmcore/(线性内存 wasm 后端):链接时用 export-memory-name 导出线性 memory;alloc(len) 返回的指针直接指向数据(实测零 header 偏移),宿主用 Uint8Array 视图批量写入像素后调用 process。

    一个诚实的性能观察:在浏览器里对同一套滤镜做基准对比,MoonBit 的 js 后端反而比线性内存 wasm 快约 4–5×。原因是 V8 对 JS 后端产物做了深度 JIT 优化,而 wasm 路径还多了进/出线性内存的拷贝与运行时开销。这说明"WASM 一定更快"是一种误解——Playground 保留了引擎切换与对比按钮,你可以自己复现这个结论。

    #✅ 测试

    moon test # 默认后端(wasm-gc) moon test --target js # js 后端

    测试覆盖每个滤镜、变换、绘图原语、合成模式、字体、分析算法与编解码器,并包含畸形输入和尺寸边界;期望值均为手工推导(脉冲响应、平场不变性、已知边缘、直方图重映射、编码字节精确长度、无损往返、CRC-32/Adler-32 公开参考向量、手工汇编的 DEFLATE 与 GIF LZW 位流等),在 wasm-gc、js 与 native 后端下均通过;GitHub Actions 持续集成。

    #📮 发布到 mooncakes.io

    模块名为 0717lee/pixelforge。其他 MoonBit 项目可通过 moon add 0717lee/pixelforge 添加依赖。

    moon login # 登录 mooncakes.io moon publish # 发布

    #📄 许可证

    Affine

    pub(all) struct Affine {
    a : Double
    b : Double
    c : Double
    d : Double
    e : Double
    f : Double
    }

    Row-major 2x3 affine matrix mapping (x, y) to (a*x + b*y + c, d*x + e*y + f).

    Affine::apply

    fn Affine::apply(self : Affine, x : Double, y : Double) -> (Double, Double)

    Applies the transform to a point.

    Affine::identity

    fn Affine::identity() -> Affine

    Identity transform.

    Affine::invert

    fn Affine::invert(self : Affine) -> Affine?

    Inverse transform, or None when the matrix is singular (determinant close to zero) and cannot be inverted.

    Affine::rotation

    fn Affine::rotation(degrees : Double) -> Affine

    Rotation about the origin. Positive angles rotate clockwise on screen (y grows downward in image coordinates), matching rotate90.

    Affine::scaling

    fn Affine::scaling(sx : Double, sy : Double) -> Affine

    Scaling about the origin.

    Affine::shear

    fn Affine::shear(shx : Double, shy : Double) -> Affine

    Shear: x' = x + shx*y, y' = shy*x + y.

    Affine::then

    fn Affine::then(self : Affine, next : Affine) -> Affine

    Composition: returns the transform that applies self first and next second (next * self as matrices).

    Affine::translation

    fn Affine::translation(dx : Double, dy : Double) -> Affine

    Translation by (dx, dy).

    BlendMode

    pub(all) enum BlendMode {
    Normal
    Multiply
    Screen
    Overlay
    Darken
    Lighten
    Difference
    Add
    }

    Separable blend modes applied per channel before alpha compositing.

    BoundingBox

    pub(all) struct BoundingBox {
    min_x : Int
    min_y : Int
    max_x : Int
    max_y : Int
    }

    Inclusive pixel bounds for one connected component.

    ComponentStats

    pub(all) struct ComponentStats {
    label : Int
    area : Int
    bbox : BoundingBox
    centroid : (Double, Double)
    min_x : Int
    min_y : Int
    max_x : Int
    max_y : Int
    centroid_x : Double
    centroid_y : Double
    }

    Measurements for one connected foreground component.

    centroid_x and centroid_y are arithmetic means of the foreground pixel coordinates (pixel centres are represented by their integer coordinates). The bounding box is inclusive: a one-pixel component has equal minimum and maximum coordinates on both axes.

    ContourPoint

    pub(all) struct ContourPoint {
    x : Int
    y : Int
    }

    One boundary pixel in a component contour. Coordinates are integer pixel positions with (0, 0) at the image's top-left corner.

    Corner

    pub(all) struct Corner {
    x : Int
    y : Int
    response : Double
    }

    One detected Harris corner. Coordinates use integer pixel positions.

    Filter

    pub(all) enum Filter {
    Grayscale
    Invert
    Brightness(Int)
    Contrast(Double)
    Blur
    Sharpen
    Emboss
    Edges
    Sobel
    Sepia
    Threshold(Int)
    Pixelate(Int)
    Median
    HistogramEqualize
    FlipHorizontal
    FlipVertical
    Posterize(Int)
    Gamma(Double)
    Vignette(Double)
    Scharr
    Canny(Int)
    Otsu
    DitherMono
    }

    A filter operation that can be composed into a [Pipeline].

    Each constructor corresponds to one of the stable apply_filter_id operations. Keeping the operation as an enum means callers cannot create a pipeline with an unknown filter id, while the existing numeric API remains available for host bindings.

    GifFrame

    pub(all) struct GifFrame {
    image : Image
    left : Int
    top : Int
    delay_cs : Int
    disposal : Int
    transparent_index : Int
    }

    A decoded GIF image descriptor. image contains the descriptor's own pixels (without compositing against the logical screen); left/top locate it in that screen. delay_cs is the Graphic Control Extension delay in hundredths of a second. disposal is the GIF disposal method (0 when unspecified), and transparent_index is -1 when transparency is not enabled for this frame.

    Image

    pub(all) struct Image {
    width : Int
    height : Int
    data : FixedArray[Byte]
    }

    An 8-bit RGBA raster image.

    Pixels are stored row-major in data, four bytes per pixel in R, G, B, A order, so data.length() == width * height * 4. This layout matches the browser ImageData.data buffer, which lets a <canvas> hand its pixels to the library without any conversion step.

    Image::adaptive_mean

    fn Image::adaptive_mean(self : Image, radius : Int, bias : Int) -> Image

    Applies a local mean threshold. bias is subtracted from the local mean, so a positive bias makes foreground detection more permissive. It is clamped to [-255, 255], the useful luma range, to keep extreme host values deterministic. Window clipping and alpha handling match sauvola.

    Image::add_gaussian_noise

    fn Image::add_gaussian_noise(self : Image, seed : UInt64, sigma : Double) -> Image

    Adds zero-mean Gaussian noise with standard deviation sigma (in luma steps) to R, G and B; alpha is untouched. The normal deviate is the classic CLT approximation (sum of 12 uniforms minus 6), which is branch-free and deterministic. sigma <= 0 returns a copy.

    Image::add_salt_pepper

    fn Image::add_salt_pepper(self : Image, seed : UInt64, density : Double) -> Image

    Salt-and-pepper noise: each pixel independently becomes pure white ("salt") or pure black ("pepper") with probability density / 2 each. density is clamped into [0, 1]; alpha is preserved. Deterministic for a given seed.

    Image::adjust_lightness

    fn Image::adjust_lightness(self : Image, delta : Double) -> Image

    Shifts every pixel's HSL lightness by delta (in [-1, 1]), clamping the result into [0, 1]. Positive values lighten toward white while preserving hue; negative values darken toward black. delta == 0 returns a copy.

    Image::affine

    fn Image::affine(self : Image, t : Affine) -> Image

    Applies an affine transform, keeping the canvas size. Each output pixel is inverse-mapped into the source and bilinearly sampled; areas with no source coverage become transparent. Aborts on singular transforms.

    Image::apply_filter_id

    fn Image::apply_filter_id(self : Image, filter_id : Int, amount : Double) -> Image

    Applies a filter selected by a numeric id. This single dispatch table is shared by every host binding — the js browser binding, the linear-memory wasm binding, and the native CLI — so they can never drift apart.

    idfilteramount
    0grayscale—
    1invert—
    2brightnessdelta (−255..255)
    3contrastfactor (0.0..3.0)
    4gaussian blur—
    5sharpen—
    6emboss—
    7laplacian edges—
    8sobel edges—
    9sepia—
    10thresholdlevel (default 128)
    11pixelateblock size (default 8)
    12median denoise—
    13histogram equalize—
    14flip horizontal—
    15flip vertical—
    16posterizelevels (default 4)
    17gammagamma value (default 2.2)
    18vignettestrength 0..1 (default 0.5)
    19scharr edges—
    20canny edgeshigh threshold (default 100, low = high/2)
    21otsu auto threshold—
    22floyd–steinberg dither (mono)—

    Image::apply_pipeline

    fn Image::apply_pipeline(self : Image, pipeline : Pipeline) -> Image

    Applies a typed filter pipeline to an image.

    Image::auto_contrast

    fn Image::auto_contrast(self : Image) -> Image

    Auto-contrast: linearly stretches the luma range [luma_min, luma_max] to the full [0, 255], applying the same scale to every channel so hues are preserved. A flat image (min == max) is returned unchanged.

    Image::average_hash

    fn Image::average_hash(self : Image) -> UInt64

    Average hash (aHash): bit i = y*8 + x is set when the luma of cell (x, y) in the 8x8 thumbnail is strictly greater than the thumbnail mean. Robust to scaling and mild blur; brightness inversion flips every bit.

    Image::bilateral

    fn Image::bilateral(self : Image, radius : Int, sigma_space : Double, sigma_range : Double) -> Image

    Applies the bilateral filter with the given neighborhood radius, spatial sigma (pixels) and range sigma (luma steps, 0..255 scale). radius <= 0 returns a copy; non-positive sigmas are clamped to a small positive value. Alpha is preserved.

    Image::blur

    fn Image::blur(self : Image) -> Image

    Gaussian blur convenience wrapper.

    Image::box_blur

    fn Image::box_blur(self : Image, radius : Int) -> Image

    Box blur (uniform mean) of the given radius using the integral image, so each output pixel costs a constant number of lookups no matter how large the window. radius <= 0 returns a copy; the window is clamped to the image at the borders. Alpha is preserved.

    Image::brightness

    fn Image::brightness(self : Image, delta : Int) -> Image

    Shifts every channel by delta (negative darkens, positive brightens). Out-of-range results saturate at 0 and 255.

    Image::canny

    fn Image::canny(self : Image, low : Int, high : Int) -> Image

    Runs Canny edge detection with the given hysteresis thresholds (low < high, both compared against the L1 gradient magnitude |Gx| + |Gy|). Pixels above high seed edges; pixels above low survive only when 8-connected to a seed. Alpha is preserved.

    Image::composite

    fn Image::composite(self : Image, top : Image, mode : BlendMode) -> Image

    Composites top over self (source-over) with the given blend mode. Both images must have identical dimensions (aborts otherwise).

    Per pixel, following the W3C compositing model: the source color is first mixed toward B(cb, cs) by the backdrop alpha, then source-over composited: ao = as + ab*(1-as) and co = (as*cs' + (1-as)*ab*cb) / ao.

    Image::contours

    fn Image::contours(self : Image, threshold : Int) -> Array[Array[ContourPoint]]

    Returns one deterministic boundary-pixel list for every 4-connected foreground component. Empty images and images without foreground return an empty array. A one-pixel component therefore has a one-point contour.

    Image::contrast

    fn Image::contrast(self : Image, factor : Double) -> Image

    Scales contrast around the 128 mid-gray point. factor > 1.0 boosts contrast, 0.0 < factor < 1.0 flattens it, and 1.0 is a no-op.

    Image::convolve

    fn Image::convolve(self : Image, kernel : Kernel) -> Image

    Convolves the image with kernel, processing R, G and B independently and preserving alpha. Out-of-bounds neighbors are clamped to the edge. This is the compute-heavy core the WebAssembly demo is built to show off.

    Image::copy

    fn Image::copy(self : Image) -> Image

    Returns a deep copy that shares no mutable state with the original.

    Image::count_components

    fn Image::count_components(self : Image, threshold : Int) -> Int

    Counts the 4-connected foreground blobs (luma > threshold).

    Image::crop

    fn Image::crop(self : Image, x : Int, y : Int, w : Int, h : Int) -> Image

    Extracts the w x h rectangle whose top-left corner is (x, y). The requested rectangle is clamped to the source bounds, so the result is never larger than the overlap with the image; out-of-range or empty requests yield a 1x1 transparent image. Pixels are copied verbatim.

    Image::difference_hash

    fn Image::difference_hash(self : Image) -> UInt64

    Difference hash (dHash): bit i = y*8 + x is set when cell (x+1, y) of a 9x8 luma thumbnail is brighter than cell (x, y) — a horizontal gradient signature that is highly robust to global tonal changes.

    Image::dilate

    fn Image::dilate(self : Image) -> Image

    Dilation: each channel takes the 3x3 neighborhood maximum, growing bright regions by one pixel per application.

    Image::distance_transform

    fn Image::distance_transform(self : Image, threshold : Int) -> Image

    Distance transform normalized to a grayscale image: background stays black, and foreground brightness grows with distance from the edge, scaled so the deepest pixel maps to 255. Alpha is preserved.

    Image::dither_grayscale

    fn Image::dither_grayscale(self : Image, levels : Int) -> Image

    Grayscale Floyd–Steinberg dithering to levels tones (clamped to [2, 256]). The image is first reduced to luma; error diffuses in a left-to-right, top-to-bottom scan. Output is gray; alpha preserved.

    Image::dither_mono

    fn Image::dither_mono(self : Image) -> Image

    1-bit (black/white) Floyd–Steinberg dithering — the classic newsprint look. Equivalent to dither_grayscale(2).

    Image::draw_char

    fn Image::draw_char(self : Image, x : Int, y : Int, ch : Char, scale : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit

    Draws one character with its top-left corner at (x, y), each font pixel scaled to a scale x scale block (scale is clamped to >= 1).

    Image::draw_circle

    fn Image::draw_circle(self : Image, cx : Int, cy : Int, radius : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit

    Draws a circle outline centered at (cx, cy) using the midpoint circle algorithm (integer-only, 8-way symmetric). radius 0 plots one pixel; negative radii draw nothing.

    Image::draw_line

    fn Image::draw_line(self : Image, x0 : Int, y0 : Int, x1 : Int, y1 : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit

    Draws a straight line from (x0, y0) to (x1, y1) inclusive with the classic integer-only Bresenham algorithm.

    Image::draw_rect

    fn Image::draw_rect(self : Image, x : Int, y : Int, w : Int, h : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit

    Draws the 1-pixel outline of the rectangle with top-left corner (x, y) and the given size. Degenerate sizes (< 1) draw nothing.

    Image::draw_text

    fn Image::draw_text(self : Image, x : Int, y : Int, text : String, scale : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit

    Draws a text string starting at (x, y); the pen advances 6 font columns (5 glyph + 1 spacing) per character. Returns nothing; text overflowing the canvas is clipped, not wrapped.

    Image::edges

    fn Image::edges(self : Image) -> Image

    Laplacian edge convenience wrapper.

    Image::emboss

    fn Image::emboss(self : Image) -> Image

    Emboss convenience wrapper.

    Image::erode

    fn Image::erode(self : Image) -> Image

    Erosion: each channel takes the 3x3 neighborhood minimum, shrinking bright regions by one pixel per application.

    Image::fill_circle

    fn Image::fill_circle(self : Image, cx : Int, cy : Int, radius : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit

    Fills the disk dx^2 + dy^2 <= radius^2 centered at (cx, cy).

    Image::fill_rect

    fn Image::fill_rect(self : Image, x : Int, y : Int, w : Int, h : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit

    Fills the rectangle with top-left corner (x, y) and the given size.

    Image::flip_horizontal

    fn Image::flip_horizontal(self : Image) -> Image

    Horizontal mirror: dst(x, y) = src(width-1-x, y). Each pixel's four channels travel together, so alpha is preserved per pixel.

    Image::flip_vertical

    fn Image::flip_vertical(self : Image) -> Image

    Vertical mirror: dst(x, y) = src(x, height-1-y).

    Image::flood_fill

    fn Image::flood_fill(self : Image, x : Int, y : Int, r : Byte, g : Byte, b : Byte, a : Byte, tolerance : Int) -> Image

    Fills the 4-connected region around (x, y) matching the seed color (within tolerance per channel) with (r, g, b, a). Returns a new image; the original is untouched. An out-of-bounds seed returns a plain copy. If the fill color already matches the seed, the copy is returned unchanged (nothing to do), which also avoids an infinite revisit.

    Image::for_each_row

    fn Image::for_each_row(self : Image, visit : (ImageRow) -> Unit) -> Unit
    Visits rows in order without allocating row buffers.

    Image::for_each_tile

    fn Image::for_each_tile(self : Image, tile_width : Int, tile_height : Int, visit : (ImageTile) -> Unit) -> Unit
    Visits all tiles in row-major order using a zero-copy view.

    The final row or column is clipped when the image dimensions are not multiples of the requested tile size. tile_width and tile_height must both be positive. The callback may mutate pixels through the view; changes are applied directly to the source image.

    Image::from_bytes

    fn Image::from_bytes(width : Int, height : Int, data : FixedArray[Byte]) -> Image

    Wraps an existing RGBA buffer. Aborts if data does not hold exactly width * height * 4 bytes, so a malformed buffer fails fast instead of producing silently corrupt output.

    Image::gamma

    fn Image::gamma(self : Image, value : Double) -> Image

    Gamma correction through a 256-entry lookup table: out = 255 * (c / 255) ^ (1 / value). value > 1 lifts midtones, 0 < value < 1 deepens them, and 1.0 is an exact identity. A non-positive value falls back to the identity.

    Image::gaussian

    fn Image::gaussian(self : Image, radius : Int) -> Image

    Gaussian blur with the given radius (clamped to [0, 32]; radius 0 is a plain copy). Two separable binomial passes — for radius r this equals convolving with the (2r+1)² discrete Gaussian, but costs O(r) per pixel instead of O(r²).

    Image::get_pixel

    fn Image::get_pixel(self : Image, x : Int, y : Int) -> (Byte, Byte, Byte, Byte)

    Reads the (R, G, B, A) channels of the pixel at (x, y).

    Aborts when the coordinates are outside the image bounds or when a host supplies an Image record whose backing buffer does not match its size.

    Image::grayscale

    fn Image::grayscale(self : Image) -> Image

    Converts the image to grayscale using the Rec. 601 luma weights (0.299, 0.587, 0.114). The weights are scaled by 1000 so the whole computation stays in integer arithmetic and is bit-for-bit reproducible.

    Image::harris_corners

    fn Image::harris_corners(self : Image, threshold : Double, max_corners : Int) -> Array[Corner]

    Detects Harris corners using threshold as the minimum raw response and returns at most max_corners strongest local maxima.

    Image::histogram_equalize

    fn Image::histogram_equalize(self : Image) -> Image

    Histogram equalization on luma: spreads the tonal range to maximize global contrast. Builds the luma histogram, integrates it into a CDF, then remaps every pixel through the normalized CDF. Output is grayscale.

    Image::histogram_luma

    fn Image::histogram_luma(self : Image) -> FixedArray[Int]

    256-bin luma histogram (BT.601 integer weights): result[v] counts the pixels whose luma is exactly v.

    Image::histogram_rgb

    fn Image::histogram_rgb(self : Image) -> (FixedArray[Int], FixedArray[Int], FixedArray[Int])

    Per-channel 256-bin histograms, returned as (red, green, blue).

    Image::hog

    fn Image::hog(self : Image, cell_size : Int, bins : Int, block_size : Int) -> Array[Double]
    Returns a normalized unsigned HOG descriptor.

    cell_size is the side length of one cell in pixels. bins is the number of evenly spaced orientation bins over [0, pi). block_size is the side length of each normalization block in cells. The output is an Array[Double] in block-major order; its length is (cells_x - block_size + 1) * (cells_y - block_size + 1) *block_size * block_size * bins when enough complete cells are present.

    Image::hue_rotate

    fn Image::hue_rotate(self : Image, degrees : Double) -> Image

    Rotates every pixel's hue by degrees around the HSV color wheel while keeping saturation and value untouched.

    Image::integral_image

    fn Image::integral_image(self : Image) -> Integral

    Builds the summed-area table over the R, G and B channels.

    Image::invert

    fn Image::invert(self : Image) -> Image

    Produces the photographic negative by flipping each channel around 255.

    Image::label_components

    fn Image::label_components(self : Image, threshold : Int) -> (Array[Int], Int)

    Labels 4-connected foreground components. Returns (labels, count) where labels has one entry per pixel — 0 for background, 1..count for each component — in row-major order.

    Image::lbp_codes

    fn Image::lbp_codes(self : Image) -> FixedArray[Byte]
    Returns one 8-bit LBP code for every pixel in row-major order.

    For an interior pixel, bit 0 is top-left and subsequent bits proceed clockwise (top, top-right, ..., left). A bit is set when its neighbour's luma is greater than or equal to the centre luma. Border entries are zero because they cannot provide eight samples.

    Image::lbp_histogram

    fn Image::lbp_histogram(self : Image) -> FixedArray[Int]
    Returns the 256-bin histogram of radius-one LBP codes.

    Only pixels with a complete 3x3 neighbourhood contribute, so the bin sum is max(width - 2, 0) * max(height - 2, 0). The histogram is useful as a compact texture descriptor and is invariant to the image's absolute brightness when local ordering is preserved.

    Image::levels

    fn Image::levels(self : Image, black : Int, white : Int, gamma : Double) -> Image

    Levels adjustment: maps the input window [black, white] onto [0, 255] with an optional midtone gamma (1.0 = linear; > 1 brightens midtones). Values are clamped, so inputs at or below black become 0 and inputs at or above white become 255. white is clamped to stay above black.

    Image::luma_mse

    fn Image::luma_mse(self : Image, other : Image) -> Double

    Mean squared error over Rec.601 luma only. Alpha is intentionally ignored.

    Image::map_rgb

    fn Image::map_rgb(self : Image, transform : (Int, Int, Int) -> (Int, Int, Int)) -> Image

    Applies a per-pixel transform to the R, G, B channels while leaving alpha untouched, clamping every result back into [0, 255]. This is the shared engine behind the point filters below, so each concrete filter only has to express its channel math.

    Image::median

    fn Image::median(self : Image) -> Image

    3x3 median filter applied independently to R, G and B; alpha is preserved.

    Image::morph_close

    fn Image::morph_close(self : Image) -> Image

    Morphological closing (dilate then erode): fills dark pinholes smaller than the 3x3 element while roughly preserving larger shapes.

    Image::morph_open

    fn Image::morph_open(self : Image) -> Image

    Morphological opening (erode then dilate): removes bright specks smaller than the 3x3 element while roughly preserving larger shapes.

    Image::mse

    fn Image::mse(self : Image, other : Image) -> Double

    Mean squared error over all RGBA channels. The result is in channel-value squared units, in the range [0, 65025] for valid 8-bit images.

    Image::new

    fn Image::new(width : Int, height : Int) -> Image

    Creates a fully transparent black image of the given size.

    Image::otsu

    fn Image::otsu(self : Image) -> Image

    Applies Otsu's automatic threshold, returning a binary (black/white) grayscale image. Pixels with luma greater than the computed threshold become white.

    Image::otsu_threshold

    fn Image::otsu_threshold(self : Image) -> Int

    Returns the Otsu threshold in 0..255: pixels with luma strictly greater than the returned value are the "foreground" class. Chooses the t that maximizes the between-class variance wB*wF*(mB-mF)^2. Variance is accumulated in Double (the textbook formulation) to stay correct on large images where an all-integer product would overflow.

    Image::pad

    fn Image::pad(self : Image, left : Int, top : Int, right : Int, bottom : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Image

    Surrounds the image with borders of the given thickness (in pixels), filled with the color (r, g, b, a). Negative border widths are treated as zero. The result is (left+width+right) x (top+height+bottom).

    Image::pixel_count

    fn Image::pixel_count(self : Image) -> Int

    The number of pixels (not bytes) in the image.

    Image::pixelate

    fn Image::pixelate(self : Image, block : Int) -> Image

    Pixelate (mosaic): replaces each block x block tile with its average color. Edge tiles are clipped to the image bounds.

    Image::posterize

    fn Image::posterize(self : Image, levels : Int) -> Image

    Posterize (tone separation): quantizes each channel into levels evenly spaced tones, producing the classic poster/print look. levels is clamped into [2, 256]; pure integer math keeps results exactly reproducible.

    Image::psnr

    fn Image::psnr(self : Image, other : Image) -> Double

    Peak signal-to-noise ratio in decibels, derived from RGBA mse with a peak channel value of 255. Identical images return positive infinity.

    Image::regionprops

    fn Image::regionprops(self : Image, threshold : Int) -> Array[ComponentStats]

    Computes area, inclusive bounds and centroid for every foreground component. Results are ordered by increasing label, which is the same row-major discovery order returned by label_components.

    The threshold comparison is strict (luma > threshold) and connectivity is four-way (up, down, left and right). An image with no foreground pixels returns an empty array.

    Image::resize_bicubic

    fn Image::resize_bicubic(self : Image, new_width : Int, new_height : Int) -> Image

    Bicubic (Catmull-Rom) resize to new_width x new_height (both clamped to at least 1). All four channels including alpha are interpolated; the cubic can overshoot near edges, so results are clamped back to 0..255.

    Image::resize_bilinear

    fn Image::resize_bilinear(self : Image, new_width : Int, new_height : Int) -> Image

    Bilinear resize: blends the four surrounding source pixels by coverage, using center-aligned sampling with clamp-to-edge, which keeps a same-size resize an exact identity. All four channels (including alpha) are blended.

    Image::resize_nearest

    fn Image::resize_nearest(self : Image, new_width : Int, new_height : Int) -> Image

    Nearest-neighbor resize: picks the closest source pixel. Fast and exact, ideal for pixel-art style scaling. Output is new_width x new_height (both clamped to at least 1).

    Image::rotate

    fn Image::rotate(self : Image, degrees : Double) -> Image

    Rotates by an arbitrary angle (degrees, clockwise) about the image center on a same-size canvas; uncovered corners become transparent.

    Image::rotate90

    fn Image::rotate90(self : Image) -> Image

    Rotates the image 90° clockwise. The result is height x width, so this is a library-level transform and is intentionally not exposed through the fixed-size apply_filter_id dispatch.

    Image::saturate

    fn Image::saturate(self : Image, factor : Double) -> Image

    Scales saturation in HSV space: factor > 1 makes colors more vivid, 0 fully desaturates (equivalent brightness-preserving grayscale in V).

    Image::sauvola

    fn Image::sauvola(self : Image, radius : Int, k : Double, dynamic_range : Int) -> Image

    Applies Sauvola local thresholding.

    radius defines a square window of (2 * radius + 1) pixels. Nonpositive radii use the single pixel at the current coordinate. k is clamped to [0, 1], and nonpositive dynamic_range uses 1; the latter keeps invalid host input deterministic instead of dividing by zero. The threshold is mean * (1 + k * (stddev / dynamic_range - 1)).

    Image::scharr

    fn Image::scharr(self : Image) -> Image

    Scharr edge detection: same structure as Sobel but with 3/10/3 weights, which are closer to rotational symmetry and give stronger, more uniform responses on diagonal edges.

    Image::sepia

    fn Image::sepia(self : Image) -> Image

    Sepia tone: the classic warm photographic look, using the widely used Microsoft sepia coefficients scaled by 1000 for exact integer math.

    Image::set_pixel

    fn Image::set_pixel(self : Image, x : Int, y : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit

    Writes the (R, G, B, A) channels of the pixel at (x, y).

    Aborts when the coordinates are outside the image bounds or when a host supplies an Image record whose backing buffer does not match its size.

    Image::sharpen

    fn Image::sharpen(self : Image) -> Image

    Sharpen convenience wrapper.

    Image::skeletonize

    fn Image::skeletonize(self : Image, threshold : Int, max_iterations : Int) -> Image
    Returns a thinned binary image using a bounded Zhang--Suen iteration.

    Image::sobel

    fn Image::sobel(self : Image) -> Image

    Sobel edge detection with the classic 1/2/1 operators.

    Image::ssim

    fn Image::ssim(self : Image, other : Image) -> Double

    Global structural similarity (SSIM) over Rec.601 luma.

    This implementation uses one population-statistics window covering the complete image (there is no sliding-window padding or border policy), and the standard constants K1 = 0.01, K2 = 0.03, L = 255. Alpha is ignored. The result is clamped to [-1, 1] to absorb tiny floating-point overshoots at the theoretical bounds.

    Image::stats

    fn Image::stats(self : Image) -> Stats

    Computes per-channel min/max/mean and the luma min/max/mean over all pixels. For the maximum 100-megapixel image the largest channel sum is 255 * 1e8 ~= 2.55e10, which exceeds 32-bit range, so the accumulators are Int64.

    Image::threshold

    fn Image::threshold(self : Image, level : Int) -> Image

    Binary threshold: pixels whose luma is at least level become white, the rest black. Useful for masks and high-contrast stylization.

    Image::translate

    fn Image::translate(self : Image, dx : Double, dy : Double) -> Image

    Translates by a (possibly fractional) offset on a same-size canvas.

    Image::unsharp_mask

    fn Image::unsharp_mask(self : Image, radius : Int, amount : Double) -> Image

    Sharpens via out = original + amount * (original - gaussian(radius)). radius selects the detail scale (>= 1; 0 makes the mask empty and thus returns a copy); amount scales the enhancement (amount <= 0 returns a copy). Per-channel result is clamped to [0, 255]; alpha is preserved.

    Image::vignette

    fn Image::vignette(self : Image, strength : Double) -> Image

    Vignette: darkens pixels toward the corners while leaving the geometric center untouched. strength in [0, 1] is the fraction of light removed at the far corners; the falloff follows the squared distance from center.

    ImageFormat

    pub(all) enum ImageFormat {
    Png
    Gif
    Qoi
    Bmp
    Jpeg
    Webp
    Avif
    Tiff
    }

    ImageFormat::name

    fn ImageFormat::name(self : ImageFormat) -> String

    ImageMetadata

    pub(all) struct ImageMetadata {
    format : ImageFormat
    width : Int
    height : Int
    animated : Bool
    }
    Width, height and animation hint read from an image container header.

    ImageRow

    pub(all) struct ImageRow {
    image : Image
    row_y : Int
    }
    A zero-copy view of one image row for streaming scans.

    ImageRow::get_pixel

    fn ImageRow::get_pixel(self : ImageRow, x : Int) -> (Byte, Byte, Byte, Byte)
    Reads a pixel from this row.

    ImageRow::width

    fn ImageRow::width(self : ImageRow) -> Int
    Number of pixels in this row.

    ImageRow::y

    fn ImageRow::y(self : ImageRow) -> Int
    Y coordinate of this row in the source image.

    ImageTile

    pub(all) struct ImageTile {
    image : Image
    origin_x : Int
    origin_y : Int
    tile_width : Int
    tile_height : Int
    }
    A read/write view over one rectangular tile of an image.

    ImageTile::copy

    fn ImageTile::copy(self : ImageTile) -> Image
    Copies the tile into an independently-owned image.

    ImageTile::get_pixel

    fn ImageTile::get_pixel(self : ImageTile, x : Int, y : Int) -> (Byte, Byte, Byte, Byte)
    Reads a pixel relative to the tile origin.

    ImageTile::height

    fn ImageTile::height(self : ImageTile) -> Int
    Height of this tile in pixels.

    ImageTile::set_pixel

    fn ImageTile::set_pixel(self : ImageTile, x : Int, y : Int, r : Byte, g : Byte, b : Byte, a : Byte) -> Unit
    Writes a pixel relative to the tile origin without copying the tile.

    ImageTile::width

    fn ImageTile::width(self : ImageTile) -> Int
    Width of this tile in pixels.

    ImageTile::x

    fn ImageTile::x(self : ImageTile) -> Int
    Horizontal origin of this tile in the source image.

    ImageTile::y

    fn ImageTile::y(self : ImageTile) -> Int
    Vertical origin of this tile in the source image.

    Integral

    pub(all) struct Integral {
    width : Int
    height : Int
    sat : Array[Int64]
    }

    A summed-area table for one image: (width+1) x (height+1) per channel, with a zero first row/column so rectangle queries need no bounds checks.

    Integral::rect_sum

    fn Integral::rect_sum(self : Integral, c : Int, x0 : Int, y0 : Int, x1 : Int, y1 : Int) -> Int64

    Sum of channel c over the inclusive rectangle [x0, x1] x [y0, y1] (0-based pixel coordinates). Uses the standard four-corner SAT formula.

    Kernel

    pub(all) struct Kernel {
    size : Int
    weights : Array[Double]
    divisor : Double
    bias : Double
    }

    A square (odd-sized) convolution kernel plus its normalization terms.

    weights are stored row-major with size * size entries. Each output channel is (sum(weight_i * neighbor_i) / divisor) + bias, clamped back into [0, 255]. Keeping divisor and bias on the kernel lets a single convolve implementation serve blur, sharpen, emboss and edge kernels.

    Kernel::box_blur

    fn Kernel::box_blur() -> Kernel

    3x3 box blur: unweighted average of the neighborhood.

    Kernel::edges

    fn Kernel::edges() -> Kernel

    3x3 Laplacian edge kernel; flat regions collapse to black.

    Kernel::emboss

    fn Kernel::emboss() -> Kernel

    3x3 emboss kernel with a +128 bias so flat areas render as mid-gray relief.

    Kernel::gaussian_blur

    fn Kernel::gaussian_blur() -> Kernel

    3x3 Gaussian blur approximation with weights summing to 16.

    Kernel::new

    fn Kernel::new(size : Int, weights : Array[Double], divisor : Double, bias : Double) -> Kernel

    Builds a kernel, aborting if the shape is invalid (even/negative size or a weight count that does not match size * size).

    Kernel::sharpen

    fn Kernel::sharpen() -> Kernel

    3x3 sharpen: boosts the center and subtracts its 4-neighbors.

    Pipeline

    pub struct Pipeline {
    operations : Array[Filter]
    }

    An ordered, reusable sequence of image filters.

    append and then return a new pipeline and leave their receiver's operation list untouched. apply also leaves the source image unchanged, matching the copy-on-write behavior of individual filters.

    Pipeline::append

    fn Pipeline::append(self : Pipeline, filter : Filter) -> Pipeline

    Returns a new pipeline with filter appended at the end.

    Pipeline::apply

    fn Pipeline::apply(self : Pipeline, image : Image) -> Image

    Applies each operation in insertion order.

    Pipeline::from_filter

    fn Pipeline::from_filter(filter : Filter) -> Pipeline

    Creates a pipeline containing one operation.

    Pipeline::is_empty

    fn Pipeline::is_empty(self : Pipeline) -> Bool

    Whether this pipeline contains no operations.

    Pipeline::length

    fn Pipeline::length(self : Pipeline) -> Int

    Number of operations in this pipeline.

    Pipeline::new

    fn Pipeline::new() -> Pipeline

    Creates an empty pipeline. Applying it returns a deep copy of the input.

    Pipeline::then

    fn Pipeline::then(self : Pipeline, other : Pipeline) -> Pipeline

    Returns a new pipeline that applies self, then other.

    Stats

    pub struct Stats {
    min_r : Int
    max_r : Int
    mean_r : Int
    min_g : Int
    max_g : Int
    mean_g : Int
    min_b : Int
    max_b : Int
    mean_b : Int
    luma_min : Int
    luma_max : Int
    luma_mean : Int
    }

    Per-channel and luma summary of an image. Means are rounded to the nearest integer. The fields are read-only (pub): the struct is a result type, so keeping construction internal lets it gain fields later without breaking downstream code.

    avif_encode

    fn avif_encode(_image : Image) -> Array[Byte]
    AVIF encoding is unavailable on native and wasm-gc targets.

    bmp_decode

    fn bmp_decode(data : Array[Byte]) -> Image?

    Decodes an uncompressed 24- or 32-bit BMP. Returns None on malformed input (bad magic, unsupported bpp/compression, truncated pixel data). 24-bit sources decode with alpha set to 255; top-down bitmaps (negative height) are handled.

    bmp_encode

    fn bmp_encode(img : Image, with_alpha : Bool) -> Array[Byte]

    Encodes an image as an uncompressed BMP. with_alpha = true writes a 32-bit BGRA bitmap; otherwise a 24-bit BGR bitmap with padded rows.

    clamp_byte

    fn clamp_byte(value : Int) -> Byte

    Clamps an integer into the [0, 255] range and narrows it to a Byte. Channel math is done in Int to avoid wrap-around, then funnelled through this helper before being stored back into a pixel buffer.

    detect_image_format

    fn detect_image_format(data : Array[Byte]) -> ImageFormat?
    Identifies common raster containers from their signatures and brands.

    gif_decode

    fn gif_decode(data : Array[Byte]) -> Image?

    Decodes the first frame of a GIF87a/GIF89a file into an RGBA image. Supports global/local color tables, interlacing and the transparent index from the graphic control extension. Returns None on anything malformed (bad signature, truncated blocks, invalid LZW data).

    gif_decode_all

    fn gif_decode_all(data : Array[Byte]) -> Array[GifFrame]?

    Decodes every image descriptor in a GIF into independent RGBA frames.

    Frames are intentionally not composited: callers can use left, top, and disposal to implement the animation policy they need while keeping this decoder deterministic and allocation-bounded. Returns None for malformed input, including truncated extensions, invalid color tables, invalid LZW data, and files without an image descriptor.

    gif_encode

    fn gif_encode(img : Image) -> Array[Byte]
    Encodes one RGBA image as GIF89a.

    The encoder supports up to 256 RGB entries. Alpha values below 128 share one transparent palette entry. The LZW stream is deliberately literal-only with a clear code before each pixel, making the output deterministic and easy to validate across backends.

    hamming_distance

    fn hamming_distance(a : UInt64, b : UInt64) -> Int

    Number of differing bits between two 64-bit hashes (0..64). As a rule of thumb for aHash/dHash: <= 5 means "very likely the same image",
    = 20 means "clearly different".

    hsl_to_rgb

    fn hsl_to_rgb(h : Double, s : Double, l : Double) -> (Int, Int, Int)

    Converts HSL (hue in degrees, saturation/lightness in [0, 1]) back to 8-bit RGB using the standard chroma/sector decomposition.

    hsv_to_rgb

    fn hsv_to_rgb(h : Double, s : Double, v : Double) -> (Int, Int, Int)

    Converts HSV (hue in degrees, saturation/value in [0, 1]) back to 8-bit RGB using the standard sector decomposition.

    image_metadata

    fn image_metadata(data : Array[Byte]) -> ImageMetadata?
    Parses dimensions for supported headers. Returns None for truncated or valid-but-unhandled variants whose dimensions are not present in the probe.

    jpeg_decode

    fn jpeg_decode(data : Array[Byte]) -> Image?
    Decodes a baseline JPEG into RGBA8 pixels.

    jpeg_encode

    fn jpeg_encode(image : Image, quality : Int) -> Array[Byte]
    Encodes an RGBA8 image as JPEG. quality is clamped by the external codec.

    png_decode

    fn png_decode(data : Array[Byte]) -> Image?

    Decodes an 8-bit PNG (color type 6 RGBA, 2 RGB, 0 grayscale, 4 grayscale+alpha, or 3 indexed palette, no interlacing). Verifies the signature, every chunk CRC and the zlib checksum; understands all five row filters. Returns None on anything malformed or unsupported.

    png_encode

    fn png_encode(img : Image) -> Array[Byte]

    Encodes an image as an 8-bit RGBA non-interlaced PNG. Each row chooses the filter with the smallest sum of absolute signed residuals, then the filtered scanlines are written as one fixed-Huffman DEFLATE block.

    qoi_decode

    fn qoi_decode(data : Array[Byte]) -> Image?

    Decodes a QOI byte stream. Returns None on malformed input (bad magic, zero dimensions, truncated stream or unsupported channel count).

    qoi_encode

    fn qoi_encode(img : Image) -> Array[Byte]

    Encodes an image as a QOI byte stream (channels = 4, sRGB colorspace tag).

    rgb_to_hsl

    fn rgb_to_hsl(r : Int, g : Int, b : Int) -> (Double, Double, Double)

    Converts 8-bit RGB to HSL: hue in degrees [0, 360), saturation and lightness in [0, 1].

    rgb_to_hsv

    fn rgb_to_hsv(r : Int, g : Int, b : Int) -> (Double, Double, Double)

    Converts 8-bit RGB to HSV: hue in degrees [0, 360), saturation and value in [0, 1].

    rgb_to_ycbcr

    fn rgb_to_ycbcr(r : Int, g : Int, b : Int) -> (Int, Int, Int)

    Converts 8-bit RGB to BT.601 full-range YCbCr (all components 0..255).

    tiff_decode

    fn tiff_decode(data : Array[Byte]) -> Image?
    Decodes a classic uncompressed baseline TIFF into RGBA8 pixels.

    webp_encode

    fn webp_encode(image : Image) -> Array[Byte]
    Encodes an RGBA8 image as lossless WebP.

    ycbcr_to_rgb

    fn ycbcr_to_rgb(y : Int, cb : Int, cr : Int) -> (Int, Int, Int)

    Converts BT.601 full-range YCbCr back to 8-bit RGB.