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, and reads std's containers, io, math, and xml.
import malunal::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 malunal.image, whose module is malunal::image, among a target's deps:
requires:
- ../image
targets:
- name: game
type: program
deps: [malunal.image]
Layout
image/ is the module malunal::image, and each format a module beneath it, as malunal::image::png.
| 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 svgs, 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 |
<style> sheets' rules, matched by specificity |
color.sakura |
Colors as CSS writes them |
named_colors.sakura |
CSS's named colors |
paint.sakura |
Fills' and strokes' paints |
lengths.sakura |
Lengths, their units, and percentages |
matrix.sakura |
Points, transforms, and transform lists |
path.sakura |
Paths of lines and cubics, arcs, rectangles, and ellipses |
path_data.sakura |
A d attribute read |
numbers.sakura |
Numbers as CSS and SVG write them |
outline.sakura |
Paths flattened to polygons |
stroke.sakura |
Strokes made polygons, with caps, joins, and dashes |
painter.sakura |
The color of each pixel, of a color or a gradient |
raster.sakura |
Polygons filled by their coverage |
canvas.sakura |
Layers, and their compositing |
What's read
- PNG: every color type and bit depth, interlaced or not, with
tRNS. Sixteen-bit samples are rounded to eight. Chunks' CRCs and zlib's Adler-32 are checked; ancillary chunks are skipped, so color is taken as sRGB whatevergAMA,cHRM, oriCCPsay. An animated PNG gives its default image. - JPEG: baseline, extended, and progressive Huffman coding, any sampling factors, and restart markers; gray, YCbCr, RGB, and Adobe's CMYK and YCCK, without color profiles. Its samples are libjpeg's: its accurate integer IDCT, its fancy upsampling, and its YCbCr constants. Data cut short gives the image as far as it goes. Arithmetic coding, lossless JPEG, and 12-bit samples are
unsupported, and EXIF's orientation isn't applied. - SVG: the static part of SVG 1.1 icons and illustrations are made of: paths and the basic shapes;
g,use,symbol,switch, and nestedsvgviewports withviewBoxandpreserveAspectRatio; fills by either rule; strokes with caps, joins, miter limits, and dashes; colors as CSS writes them, linear and radial gradients with every spread andhrefinheritance;opacity,clip-path, andmask. Styles come from presentation attributes, then<style>sheets, whose selectors may be types, classes, IDs, and descendant and child combinators, thenstyleattributes, withinheritandcurrentColor. Its XML is read bystd::xml, entities and all, as Illustrator's files need. Text, embedded images, patterns, markers, filters, and nested viewports' clipping aren't drawn.
The SVG rasterizer covers each pixel with sixteen rows of samples, each span's coverage across them worked out exactly, and blends onto layers of premultiplied RGBA, one for each group with opacity, a clip, or a mask. Gradients' stops are blended before they're premultiplied, as browsers blend them.
What's written
- PNG: every pixel exactly, in the least color type and depth that holds them all: gray of 1, 2, 4, or 8 bits, where every pixel is gray and opaque; a palette of up to 256 colors, of 1, 2, 4, or 8 bits, its alpha in
tRNS, where that's fewer bits than gray takes; and otherwise gray with alpha, RGB, or RGBA, of 8 bits.png::options { reduced = false }writes RGBA of 8 bits whatever the pixels are, andinterlaced = truewrites Adam7's passes. Rows of 8-bit samples are each filtered by whichever of PNG's five filters leaves the least, by the sum of its bytes taken as signed, as libpng chooses, and rows of palette indices or of samples less than a byte by none. Deflate is zlib's: chains of where each three bytes were seen, its levels' table from 0, which stores, to 9, with lazy matching from 4, and each block of 16384 symbols written stored, by the fixed codes, or by Huffman codes of its own, limited to 15 bits as miniz limits them, whichever is shortest. AnsRGBchunk says the colors are sRGB's; nothing else ancillary is written. - JPEG: baseline, as libjpeg writes it by default: JFIF's YCbCr, by libjpeg's constants; Annex K's quantization tables, scaled by quality as libjpeg scales them, 90 by default; libjpeg's accurate integer DCT; and Annex K's Huffman tables. Chrominance is halved across and down by default, as libjpeg halves it,
subsampling::acrosshalves it across alone, andnonekeeps every sample. An image every pixel of which is gray is written as gray alone. JPEG holds no alpha, so each pixel's color is written however clear it is. It may be 65535 across and down at most, past which istoo_large.
Limits
max_pixels, 64 M, bounds every image read, refused as too_large before its pixels are read or drawn. PNG's data is inflated into exactly as much memory as the image needs, and no more. SVG's references nest at most 64 deep, so a use within what it refers to ends.
Speed
blossom build, then run malunal.image.bench, which writes and reads two images of 1024 by 1024 pixels, the best of three, on a Ryzen 9 9950X3D: one as a photograph is, gradients with a little noise over them, and one as an interface is, panels of flat colors. Windows' own encoders, WIC's, write the same as PNG and as JPEG of quality 90 for comparison:
| What | Written | Read | Size | WIC writes |
|---|---|---|---|---|
| PNG level 1, photograph | 58 ms | 19 ms | 1256 KiB | |
| PNG level 6, photograph | 284 ms | 17 ms | 1079 KiB | 40 ms, 1071 KiB |
| PNG level 9, photograph | 546 ms | 16 ms | 1042 KiB | |
| PNG level 6, interface | 8 ms | 3 ms | 2 KiB | 5 ms, 6 KiB |
| JPEG 90, 4:2:0, photograph | 19 ms | 15 ms | 115 KiB | 2 ms, 116 KiB |
| JPEG 90, 4:4:4, photograph | 30 ms | 17 ms | 163 KiB | |
| JPEG 90, 4:2:0, interface | 16 ms | 13 ms | 66 KiB | 1 ms, 67 KiB |
Deflate's time is in walking its chains, as zlib's is, so a level's time follows how far it looks: a noisy photograph at level 6, which looks 128 places back, takes five times level 1's. What's flat, as interfaces and icons are, is quick at any level.
Testing
blossom test runs tests/, which reads the images in tests/images/, and writes images of patterns it makes in memory and reads them back: PNG of every color type, depth, level, and interlacing, exactly; JPEG of each subsampling and of sizes of part of a block, near its colors, gray as gray, and smaller at lower quality; and files saved by their extensions. tools/test_images.ps1 writes the test images again with Windows' own encoders, from a pattern the tests work out again.
What's read was checked further against outside references, which aren't part of the repository:
- PNG: every image of PngSuite, against WIC. Those of eight bits or fewer match exactly, those of sixteen within the 1 rounding gives, and every broken one is refused.
- JPEG:
jpeg-decoder's reference images, made by libjpeg, all within 3 but a progressive one cut short, which libjpeg smooths. - SVG: drawings against Chrome's, the Ghostscript Tiger and Wikipedia's logo among them.
- Fuzzing: a checked build was given each of those cut short and with bytes changed, CRCs fixed so the changes reach past them, and faulted at none.
And what's written, against WIC's decoders: 47 PNGs of every color type, depth, level, and interlacing, 300 by 300 of noise and of a photograph among them, each read back exactly; and JPEGs of every subsampling at odd sizes, each read to the same colors this reads them as.