commit 4f62b4691f46edffd7d47d75db4242b43c599d0e Author: SoraKatadzuma Date: Wed Oct 28 08:26:26 2026 -0500 Initial Commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c6c8b36 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9fc1e46 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.blossom +tests/written.* diff --git a/README.md b/README.md new file mode 100644 index 0000000..b699d34 --- /dev/null +++ b/README.md @@ -0,0 +1,133 @@ +# image +Images read from PNG, JPEG, and SVG, and written to PNG and JPEG, each the same `image`: RGBA, eight bits a channel, in sRGB, with straight alpha, rows from the top. That's what a GPU takes as `rgba8_srgb`, so an image is a texture as it is. It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), and reads std's `containers`, `io`, `math`, and `xml`. + +```sakura +import image; + +val icon := image::load("assets/icon.svg", image::svg_size { width = 256 }) else (e) { ... }; +val photo := image::load("assets/photo.jpg") else (e) { ... }; +image::save(&photo, "out/photo.png") else (e) { ... }; # PNG, by the extension +val small := image::jpeg::encode(&photo, image::jpeg::options { quality = 80 }) else (e) { ... }; +val tight := image::png::encode(&icon, image::png::options { level = 9 }) else (e) { ... }; +``` +`image::decode(bytes)` reads bytes already in memory, and `image::format_of(bytes)` says which format they're in, by their first few. `image::encode(&picture, format)` writes bytes, `image::write_to` writes them into any `writable`, as std's `json::write_to` does, and `image::save` writes a file in the format its extension names. Each format's own `encode` takes its options. An SVG is drawn at the size asked for, its own by default, and a raster image is read at its own whatever is asked. SVG is read, and not written. + +A project reads it by requiring this folder, or its remote, and naming `image` among a target's `deps`: + +```yaml +requires: +- ../image +targets: +- name: game + type: program + deps: [image] +``` + +## Layout +`image/` is the module `image`, and each format a module beneath it. + +| Path | Holds | +|---|---| +| `image.sakura` | `image`, `image_error`, and `max_pixels` | +| `formats.sakura` | `format`, `svg_size`, and which format bytes, or an extension, say | +| `reading.sakura` | `decode` and `load`, by the format the bytes are in | +| `writing.sakura` | `encode`, `write_to`, and `save`, in the format asked for or the extension names | + +`png/`, `image::png`: + +| Path | Holds | +|---|---| +| `png.sakura` | The color types, Adam7's passes, and the chunks read: `decode` | +| `header.sakura` | `IHDR`, `PLTE`, and `tRNS` | +| `pixels.sakura` | Rows of samples made RGBA, RGBA made rows, and the sizes of rows | +| `filters.sakura` | Filters undone, and the one leaving the least chosen | +| `inflate.sakura` | zlib's data inflated | +| `deflate.sakura` | Runs found back through chains of hashes, at each level | +| `blocks.sakura` | Bits written, and each block written stored, by the fixed codes, or by its own | +| `huffman.sakura` | Codes read by table, and codes made of how often each symbol is used | +| `symbols.sakura` | DEFLATE's lengths and distances, and their symbols | +| `checksums.sakura` | CRC-32 and Adler-32 | +| `colors.sakura` | What colors an image holds, and the color type and depth chosen of them | +| `encode.sakura` | `options` and `encode`: rows filtered and deflated, then the chunks | + +`jpeg/`, `image::jpeg`: + +| Path | Holds | +|---|---| +| `jpeg.sakura` | Zigzag order, and the markers read: `decode` | +| `markers.sakura` | The decoder's state, and the frame, tables, and scans' headers | +| `huffman.sakura` | Huffman tables, and the bits of a scan read | +| `scan.sakura` | A scan's blocks decoded, sequential and progressive | +| `idct.sakura` | The inverse DCT | +| `color.sakura` | Components upsampled, and pixels' colors of them | +| `tables.sakura` | Annex K's quantization and Huffman tables, and quality's scaling | +| `planes.sakura` | YCbCr, or gray, of an image's pixels, padded and subsampled | +| `fdct.sakura` | The forward DCT, and quantizing | +| `entropy.sakura` | Huffman codes, the bits of a scan written, and each block coded | +| `encode.sakura` | `options`, `subsampling`, and `encode`: the markers, then the scan | + +`svg/`, `image::svg`: + +| Path | Holds | +|---|---| +| `svg.sakura` | The renderer, and its size worked out: `render` | +| `draw.sakura` | The document indexed, styled, and walked, and layers for opacity, clips, and masks | +| `viewports.sakura` | Nested `svg`s, `use`, `symbol`, `viewBox`, and `preserveAspectRatio` | +| `shapes.sakura` | Each shape's path, filled and stroked | +| `gradients.sakura` | Paints, and linear and radial gradients by their `href` chains | +| `masks.sakura` | `clipPath` and `mask` | +| `style.sakura` | Each element's properties, set and inherited | +| `sheet.sakura` | ` + + + + + + """); + t.expects(made.at(5, 5) == rgba(255, 165, 0, 255)); + t.expects(made.at(15, 5) == rgba(255, 0, 0, 255)); + t.expects(made.at(25, 5) == rgba(0, 255, 0, 255)); + val faint := made.at(35, 5); + t.expects(faint[0] == 128 && faint[3] >= 127 && faint[3] <= 128); +} + +@test def refuses_broken_svg(t: &mut tester): void { + t.expects(fails(image::decode(""), image::image_error::malformed)); + t.expects(fails(image::decode(""), image::image_error::malformed)); + t.expects(fails(image::decode(""), image::image_error::too_large)); + # Path data broken partway is drawn as far as it goes. + val partial := draw(""); + t.expects(partial.at(5, 5) == rgba(0, 0, 0, 255)); +} diff --git a/tools/bench.sakura b/tools/bench.sakura new file mode 100644 index 0000000..0baf941 --- /dev/null +++ b/tools/bench.sakura @@ -0,0 +1,123 @@ +#! Times writing and reading each format, of two images of 1024 by 1024 pixels: +#! one as a photograph is, smooth gradients with a little noise over them, and +#! one as an interface is, flat colors with hard edges. PNG is written at levels +#! 1, 6, and 9, and JPEG at quality 90, its chrominance halved both ways and +#! kept whole. Each is the best of three. +#! +#! `blossom build`, then run `image.bench`, as an executable: the VM's times +#! aren't the program's. + +import std::io; +import std::time; +import image; + +const side: u32 = 1024; +const tries: u32 = 3; + +# A photograph's worth: gradients across, down, and along the diagonal, and +# noise of a few levels over them. +def photograph(): image::image { + var pixels := vector::::new(); + pixels.reserve((side as u64) * (side as u64) * 4); + var seed: u32 = 12345; + for y in 0..side { + for x in 0..side { + seed = seed ^ (seed << 13); + seed = seed ^ (seed >> 17); + seed = seed ^ (seed << 5); + val noise := (seed % 9) as i32 - 4; + pixels.append(clamp((x * 255 / side) as i32 + noise)); + pixels.append(clamp((y * 255 / side) as i32 + noise)); + pixels.append(clamp(((x + y) * 255 / (2 * side)) as i32 - noise)); + pixels.append(255); + } + } + return image::image { width = side, height = side, pixels = move(pixels) }; +} + +# An interface's worth: panels of a few flat colors, each with a border. +def interface(): image::image { + var pixels := vector::::new(); + pixels.reserve((side as u64) * (side as u64) * 4); + for y in 0..side { + for x in 0..side { + val panel := (x / 128 + (y / 96) * 3) % 5; + val border := x % 128 < 2 || y % 96 < 2; + val color: u32 = border ? 0x303030 : panel_colors[panel as u64]; + pixels.append((color >> 16) as u8); + pixels.append((color >> 8) as u8); + pixels.append(color as u8); + pixels.append(255); + } + } + return image::image { width = side, height = side, pixels = move(pixels) }; +} + +const panel_colors: u32[5] = [0xF0F0F0, 0x2D6CDF, 0xE8E8E8, 0xFFFFFF, 0xD04040]; + +def clamp(value: i32): u8 { + return (value < 0 ? 0 : (value > 255 ? 255 : value)) as u8; +} + +# Writes an image, then reads it, each the best of a few tries, and says how +# long each took and how many bytes it was. +def time_png(what: strview, picture: &image::image, level: u32): void { + var best_write: f64 = 1e30; + var best_read: f64 = 1e30; + var size: u64 = 0; + for _ in 0..tries { + var at := instant::now(); + val written := image::png::encode(picture, image::png::options { level = level }) else (_) { println("couldn't write"); return; }; + val wrote := at.elapsed().in_nanoseconds as f64; + at = instant::now(); + val read := image::decode(written.view()) else (_) { println("couldn't read"); return; }; + val took := at.elapsed().in_nanoseconds as f64; + best_write = wrote < best_write ? wrote : best_write; + best_read = took < best_read ? took : best_read; + size = written.length; + if read.pixels.length != picture.pixels.length { + println("read back another size"); + } + } + report(what, best_write, best_read, size); +} + +def time_jpeg(what: strview, picture: &image::image, chroma: image::jpeg::subsampling): void { + var best_write: f64 = 1e30; + var best_read: f64 = 1e30; + var size: u64 = 0; + for _ in 0..tries { + var at := instant::now(); + val written := image::jpeg::encode(picture, image::jpeg::options { quality = 90, chroma = chroma }) else (_) { println("couldn't write"); return; }; + val wrote := at.elapsed().in_nanoseconds as f64; + at = instant::now(); + val read := image::decode(written.view()) else (_) { println("couldn't read"); return; }; + val took := at.elapsed().in_nanoseconds as f64; + best_write = wrote < best_write ? wrote : best_write; + best_read = took < best_read ? took : best_read; + size = written.length; + if read.pixels.length != picture.pixels.length { + println("read back another size"); + } + } + report(what, best_write, best_read, size); +} + +def report(what: strview, wrote: f64, read: f64, size: u64): void { + val pixels := (side as f64) * (side as f64); + println($"{what}: written in {(wrote / 1000000) as u64} ms ({(pixels * 1000 / wrote) as u64} MP/s), read in {(read / 1000000) as u64} ms, {size / 1024} KiB"); +} + +def main(): void { + val photo := photograph(); + val flat := interface(); + time_png("PNG level 1, photograph", &photo, 1); + time_png("PNG level 6, photograph", &photo, 6); + time_png("PNG level 9, photograph", &photo, 9); + time_png("PNG level 1, interface", &flat, 1); + time_png("PNG level 6, interface", &flat, 6); + time_png("PNG level 9, interface", &flat, 9); + time_jpeg("JPEG 90, 4:2:0, photograph", &photo, image::jpeg::subsampling::both); + time_jpeg("JPEG 90, 4:4:4, photograph", &photo, image::jpeg::subsampling::none); + time_jpeg("JPEG 90, 4:2:0, interface", &flat, image::jpeg::subsampling::both); +} diff --git a/tools/test_images.ps1 b/tools/test_images.ps1 new file mode 100644 index 0000000..8beec52 --- /dev/null +++ b/tools/test_images.ps1 @@ -0,0 +1,78 @@ +# Writes the images `tests/` reads into `tests/images/`, with Windows' own encoders, which are no +# part of image's decoders. Each is 24 by 20 pixels of a pattern the tests work out again, as +# `tests/support.sakura` does, red rising across, green down, and blue along the diagonal: +# +# r = 10x, g = 12y, b = 5(x + y), a = 55 + 8x where it has alpha +# +# powershell -File tools/test_images.ps1 +Add-Type -AssemblyName PresentationCore +$out = Join-Path $PSScriptRoot "..\tests\images" +New-Item -ItemType Directory -Force $out | Out-Null +$width = 24; $height = 20 +$formats = [System.Windows.Media.PixelFormats] + +# The pattern as BGRA, and as the samples of the other formats. +function Pattern([string]$kind) { + $bytes = New-Object System.Collections.Generic.List[byte] + for ($y = 0; $y -lt $height; $y++) { + for ($x = 0; $x -lt $width; $x++) { + $r = 10 * $x; $g = 12 * $y; $b = 5 * ($x + $y); $a = 55 + 8 * $x + switch ($kind) { + "bgra" { $bytes.Add($b); $bytes.Add($g); $bytes.Add($r); $bytes.Add($a) } + "bgr" { $bytes.Add($b); $bytes.Add($g); $bytes.Add($r) } + "gray" { $bytes.Add($g) } + "gray16" { $v = $g * 257; $bytes.Add($v -band 0xFF); $bytes.Add($v -shr 8) } + "rgba64" { foreach ($c in @($r, $g, $b, $a)) { $v = $c * 257; $bytes.Add($v -band 0xFF); $bytes.Add($v -shr 8) } } + "index" { $bytes.Add([byte]((($x -shr 2) + ($y -shr 2) * 6) % 16)) } + "bw" { } + } + } + } + return ,$bytes.ToArray() +} + +function Save($encoder, [string]$name, $source) { + $encoder.Frames.Add([System.Windows.Media.Imaging.BitmapFrame]::Create($source)) + $stream = [System.IO.File]::Create((Join-Path $out $name)) + $encoder.Save($stream) + $stream.Close() +} + +function Source($format, [byte[]]$pixels, [int]$bitsPerPixel, $palette = $null) { + $stride = [int][Math]::Ceiling($width * $bitsPerPixel / 8.0) + return [System.Windows.Media.Imaging.BitmapSource]::Create($width, $height, 96, 96, $format, $palette, $pixels, $stride) +} + +function Png([string]$name, $source, [bool]$interlaced = $false) { + $encoder = New-Object System.Windows.Media.Imaging.PngBitmapEncoder + if ($interlaced) { $encoder.Interlace = [System.Windows.Media.Imaging.PngInterlaceOption]::On } + Save $encoder $name $source +} + +Png "rgba8.png" (Source $formats::Bgra32 (Pattern "bgra") 32) +Png "rgb8.png" (Source $formats::Bgr24 (Pattern "bgr") 24) +Png "gray8.png" (Source $formats::Gray8 (Pattern "gray") 8) +Png "gray16.png" (Source $formats::Gray16 (Pattern "gray16") 16) +Png "rgba16.png" (Source $formats::Rgba64 (Pattern "rgba64") 64) +Png "interlaced.png" (Source $formats::Bgra32 (Pattern "bgra") 32) $true + +# Sixteen colors, entry i being (16i, 255 - 16i, 8i), each with alpha 255 - 8i. +$colors = New-Object System.Collections.Generic.List[System.Windows.Media.Color] +for ($i = 0; $i -lt 16; $i++) { $colors.Add([System.Windows.Media.Color]::FromArgb(255 - 8 * $i, 16 * $i, 255 - 16 * $i, 8 * $i)) } +$palette = New-Object System.Windows.Media.Imaging.BitmapPalette -ArgumentList (,$colors) +$indices = Pattern "index" +$packed = New-Object byte[] (12 * $height) +for ($i = 0; $i -lt $indices.Length; $i++) { + $row = [Math]::Floor($i / $width); $column = $i % $width + $packed[$row * 12 + ($column -shr 1)] = $packed[$row * 12 + ($column -shr 1)] -bor ($indices[$i] -shl (4 * (1 - ($column -band 1)))) +} +Png "palette4.png" (Source $formats::Indexed4 $packed 4 $palette) + +$jpeg = New-Object System.Windows.Media.Imaging.JpegBitmapEncoder +$jpeg.QualityLevel = 95 +Save $jpeg "rgb.jpg" (Source $formats::Bgr24 (Pattern "bgr") 24) +$gray = New-Object System.Windows.Media.Imaging.JpegBitmapEncoder +$gray.QualityLevel = 95 +Save $gray "gray.jpg" (Source $formats::Gray8 (Pattern "gray") 8) + +Get-ChildItem $out | ForEach-Object { "$($_.Name) $($_.Length)" }