arsd image modules (D)
The image half of the arsd collection: one 8-bit RGBA Color, two GC-allocated image classes behind a MemoryImage interface, a set of standalone decoders (arsd.png, arsd.jpeg, arsd.bmp, arsd.svg and others) that each return that interface, an arsd.image facade that sniffs the format, and arsd.simpledisplay, which turns any MemoryImage into a native window bitmap.
| Field | Value |
|---|---|
| Language | D; since January 1, 2024 the repository targets the OpenD dialect (README.md) |
| License | BSL-1.0 for the package (dub.json); per file, png.d says "released into the public domain" (png.d), jpeg.d is an Unlicense port of jpgd (jpeg.d), svg.d carries the NanoSVG zlib-style notice (svg.d) |
| Repository | adamdruppe/arsd, dub package arsd-official with sub-packages color_base, png, jpeg, bmp, svg, image_files, simpledisplay |
| Revision read | 11491fa8bb9594eb5bd33e2556a9e395d19f30dc (October 24, 2026) |
| Documentation | In-source DDoc, rendered at arsd-official.dpldocs.info |
| Category | D landscape: GC-based codec collection and windowing consumer |
| Tier | B |
| Last reviewed | November 15, 2026 |
NOTE
Every quote was read with git show 11491fa8b:<path> from a shallow clone, and every cited path checked with git cat-file -e. Claims marked verified were run in a scratch directory (/tmp/tierb-arsd-image) against copies of color.d, core.d, png.d, jpeg.d, bmp.d, image.d, svg.d, targa.d, pcx.d, dds.d and imageresize.d, compiled with DMD 2.112.1. core.d does not parse with that compiler: line 8956 uses the OpenD-only private(this), and the demo replaced it with private. Inputs were generated by a small D program, ImageMagick 7.1.2, and PngSuite files from the pinned libpng source ($SPARKLES_FLAKE_INPUT_LIBPNG_SRC/contrib/pngsuite). Everything else is documented, not run.
Independent verification on November 14 and November 15, 2026 reran the probes in fresh pinned source copies under /tmp (/tmp/verify-arsd-image, /tmp/arsd-verifier-pass2) with the same single-line core.d patch, invoking DMD 2.112.1 and ImageMagick 7.1.2 through nix develop /home/petar/code/repos/mine/sparkles-images -c … (dmd -Isrc -i probe.d -ofprobe). All seven hostile-input cases (including the jpeg.d(710) stack trace), the three tRNS cases, the alpha conversion and alphaBlend were reproduced, along with probes for negative TrueColorImage dimensions, nsvgParse on HTML and readJpeg on a 551-byte relative filename. The OpenGlTexture.bindFrom padding defect was verified by reading game.d.
Overview
What it solves
arsd is a collection of mostly independent single-file modules. The image modules let a program load a picture from disk or memory, edit pixels, write PNG, JPEG or BMP, and show the result in a window. PNG uses zlib (png.d); native display also needs platform libraries. arsd.color is the shared vocabulary:
Base module for working with colors and in-memory image pixmaps. Also has various basic data type definitions that are generally useful with images like [Point], [Size], and [Rectangle]. (
color.d)
and the facade states its job and its build caveat:
This file imports all available image decoders in the arsd library, and provides convenient functions to load image regardless of it's format. Main functions: [loadImageFromFile] and [loadImageFromMemory]. (
image.d)
Design philosophy
Convenience and few dependencies rank above generality. The pixel type is fixed (ubyte[4]), images are classes owned by the GC, and the format-specific detail is flattened into one of two classes on load. The png.d header says what is lost:
Greyscale pngs and bit depths other than 8 are converted for the ease of the MemoryImage interface. If you need more detail, try [PNG] and [getDatastream] etc. (
png.d)
arsd.color keeps its compile cost low on purpose ("importing phobos explodes the size of this code 10x, so not doing it.", color.d), and the decoders are written so that each one is usable on its own: arsd.jpeg adds its MemoryImage API only static if (__traits(compiles, { import arsd.color; })) (jpeg.d), and MemoryImage.fromImage reaches arsd.image the same way (color.d). Optional coupling through compile-time introspection on module availability is the collection's packaging idiom.
How it works
Color and the two image classes
Color is four bytes, straight alpha, with ref accessors over the array so it also works in CTFE (color.d):
struct Color {
ubyte[4] components; /// [r, g, b, a]
pragma(inline, true) ref inout(ubyte) r() inout scope return { return components[0]; }
// g, b, a likewise; a == 255 is opaque
}MemoryImage is a runtime interface: width, height, getPixel, setPixel, clone, getAsTrueColorImage and a low-level clearInternal that frees storage early (color.d). The module comment explains why there are two implementations rather than one:
Why are they separate classes? I think the operations on the two of them are necessarily different. There's a whole bunch of operations that only really work on truecolor (blurs, gradients), and a few that only work on indexed images (palette swaps). (
color.d)
TrueColorImageholdsData imageData, a struct aroundubyte[] bytes"Stored left to right, top to bottom, no padding", with a@trustedcolorsproperty that reinterprets the same bytes asColor[](color.d).IndexedImageholdsColor[] paletteandubyte[] data, one index per pixel, at most 256 entries;getPixelreturns transparent black for an index past the palette (color.d).
The image classes have no explicit stride or sub-image view and no sample storage beyond RGBA8 or 8-bit indices. A greyscale PNG becomes a TrueColorImage with r == g == b. A third class, TrueColorImageWithoutAlpha, exists only inside a /+ … +/ comment (color.d).
Decoders
Each decoder exposes a low-level layer and a MemoryImage layer:
| Module | Low level | MemoryImage entry points | Errors |
|---|---|---|---|
arsd.png | PNG (chunk list), getDatastream, lazy pngFromBytes / LazyPngFile over an input range of byte chunks | readPng, readPngFromBytes, imageFromPng, writePng, writePngLazy | Exception; assert on invariants |
arsd.jpeg | jpeg_decoder (a D port of jpgd): constructor, begin_decoding, decode per scanline | readJpeg, readJpegFromMemory, readJpegFromStream, writeJpeg, encodeJpeg | null plus the global lastJpegError, or a thrown Exception |
arsd.bmp | readBmpIndirect(fread delegate) | readBmp(filename), readBmp(bytes), writeBmp | Exception |
arsd.svg | nsvgParse to an NSVG shape list, rasterize into a caller buffer (a NanoSVG port) | readSvg in arsd.image | null |
arsd.image | guessImageFormatFromExtension, guessImageFormatFromMemory | loadImageFromFile, loadImageFromMemory | Exception for unknown or GIF |
arsd.image public-imports the decoders (including TGA, PCX and DDS) and dispatches with a final switch on ImageFileFormat (image.d). File loading trusts the extension first; only an unknown extension reads the file and sniffs bytes. GIF is detected and refused: "arsd has no GIF loader yet". Animated PNG lives in a separate module, arsd.apng, not reached from the facade.
The PNG path
readPng(in ubyte[] data) copies every chunk into a GC Chunk (size, type, payload, checksum) without checking the checksum (png.d). imageFromPng reads IHDR, allocates a TrueColorImage or IndexedImage of the full declared size, then pulls scanlines through LazyPngFile!(Chunk[]), unfilters each line and converts it into the image (png.d). Its rawDatastreamByChunk drives zlib (etc.c.zlib) with malloced buffers (png.d). Sixteen-bit samples keep the high byte ("discarding the least significant byte as we can't store it anyway", png.d). The range-based reader pngFromBytes does verify CRCs (enforce(n.checksum == crcPng(...)), png.d); both paths use LazyPngFile, whose comment says, "FIXME: it doesn't handle interlaced files." (png.d).
The JPEG path
jpeg.d is @system throughout and allocates decoder state with malloc in a linear block allocator (jpgd_malloc, alloc). Errors inside the decoder go through stop_decoding, which records m_error_code and throws: "This method handles all errors. It will never return. It could easily be changed to use C++ exceptions." (jpeg.d). begin_decoding and decode catch Exception and return JPGD_FAILED (jpeg.d); the constructor does not. readJpegFromStream turns failures after the header into null plus a module-global LastJpegError(stage, code, details) (jpeg.d, jpeg.d). It always requests four components, so greyscale and YCbCr both land in a TrueColorImage, and then applies the EXIF orientation by default with the ImageTransforms helpers in arsd.color (autoRotateBasedOnExifOrientation, jpeg.d; jpeg.d). Width and height are capped at JPGD_MAX_WIDTH = JPGD_MAX_HEIGHT = 16384 (jpeg.d).
How simpledisplay consumes images
arsd.simpledisplay defines its own final class Image, a native bitmap (an XImage, with MIT-SHM when available, or a Windows DIB section). Image.fromMemoryImage(MemoryImage i, bool enableAlpha = false, bool premultiply = true) calls getAsTrueColorImage, allocates the native image and copies through setRgbaBytes (simpledisplay.d). On X11 the copy swizzles RGBA to BGRA and, when alpha is on and premultiply is set, calls premultiplyBgra per pixel; reading back unpremultiplies (simpledisplay.d). On Windows it writes a bottom-up DIB, 24-bit rows padded to four bytes or 32-bit premultiplied (simpledisplay.d). The class documentation tells users to free it explicitly because it may hold X server shared memory that outlives the process, and that alpha only blends through Sprite:
You can load an image with an alpha channel, but you cannot draw that in the current implementation. If you want alpha blending when drawing, use [Sprite] instead. (
simpledisplay.d)
arsd.game uploads a TrueColorImage to OpenGL with OpenGlTexture.bindFrom, padding non-power-of-two sizes into a malloced buffer (game.d).
Analysis
1. Pixel and memory model
The truecolour layout is interleaved 8-bit RGBA, top-down, no padding, row stride implicit as width * 4, alongside an 8-bit indexed variant. It is narrower than the Go standard library's (see Go image), which carries Stride and Rect so a sub-image is a view. An arbitrary rectangular crop cannot be represented as a view in these classes, and native bitmap conversion uses per-pixel loops. Sizes are int; TrueColorImage constructors assert cast(ulong)w * h * 4 <= size_t.max and the allocating overload uses new ubyte[cast(size_t)w * h * 4] (color.d). This does not validate positivity: verified, new TrueColorImage(-1, -1) succeeds with dimensions -1 by -1 and four bytes of storage on the tested 64-bit build, where unsigned multiplication wraps.
2. Genericity mechanism
Classes and one interface. Image storage dispatch uses runtime type (cast(IndexedImage) mi, as writePngToArray does, png.d) rather than a generic image concept. Optional module coupling uses __traits(compiles, { import arsd.image; }); this does not describe all introspection elsewhere in color.d. Compare the static concept of ae.utils.graphics and its @nogc fork in Dplug: the same ecosystem chose the opposite end of the spectrum for a product that renders every frame.
3. Colour and metadata
No colour management. PNG gAMA, cHRM, sRGB and iCCP are not read (a grep of png.d finds no reference to them), and JPEG reads one EXIF tag, orientation (if(tagId == 0x0112 && …), "for now all i care about is orientation lol", jpeg.d). The tRNS chunk is honoured for indexed PNGs only: verified, PngSuite ftbrn2c08.png (truecolour with a colour key) and ftbbn0g04.png (greyscale with a key) decode with 0 pixels below alpha 255, while ImageMagick reports transparency in both (mean alpha 0.558 and 464 fully transparent pixels); the indexed ftbbn3p08.png gives 454 transparent pixels. Alpha is straight in MemoryImage and premultiplied in native images; the conversions are 8-bit integer and lossy (verified: premultiplyBgra then unPremultiplyRgba takes straight [10, 200, 100, 10] to [0, 178, 76, 10], color.d). Blending says what it does not do: "WARNING! This function does blending in RGB space, and RGB space is not linear!" (color.d). The module does carry ColorF, Oklab conversion and sRGB transfer helpers (color.d), unused by the codecs. See straight and premultiplied alpha.
4. I/O and codec architecture
Three different I/O shapes coexist. PNG is whole-buffer (eager, readPng) or pull over an input range of byte chunks (pngFromBytes); JPEG and BMP are pull through a caller-supplied read delegate (JpegStreamReadFunc, readBmpIndirect's fread); SVG parses a whole string. None is suspendable: a delegate that has no bytes yet can only report end of file or error. The facade is a closed enum and final switch, not a registry; compare Go's RegisterFormat (Go image). Sniffing is coarse: any buffer longer than six bytes that starts with < is SVG (image.d). Verified: loadImageFromMemory on the 38-byte text <html><body>not an image</body></html> returns a 1x1 transparent image, not an error, because nsvgParse ignores non-SVG elements and returns a non-null NSVG struct with width == 0, height == 0 and shapes is null (svg.d), and readSvg then allocates cast(int) image.width + 1 by cast(int) image.height + 1 (image.d).
5. Hostile input and safety
Limits are per format and mostly absent. JPEG has its 16384 cap; the TGA and PCX sniffers and loaders refuse dimensions above 32000 (image.d, targa.d, pcx.d); ddsDetect caps at 65500 (dds.d); imageresize caps 65536 (imageresize.d). PNG and BMP allocate whatever the header declares before reading pixel data, and readPng sizes a chunk's payload before checking it against the input:
n.payload.length = n.size; // allocates first
if(pos + n.size > data.length)
throw new Exception(format("malformed png, chunk '%s' %d @ %d longer than data %d", ...));(png.d). Verified under a 2 GB address-space limit (ulimit -v 2000000), each input below decoded through loadImageFromMemory:
| Input (bytes) | Result |
|---|---|
valid 2x2 PNG with a corrupted IDAT CRC (76) | decodes normally; pngFromBytes on the same file throws "Chunk checksum didn't match" |
PNG whose IHDR declares 40000x40000 RGBA (76) | core.exception.OutOfMemoryError |
PNG with a tEXt chunk declaring 0xFFFFFFF0 bytes (46) | core.exception.OutOfMemoryError, not the "malformed png" exception |
| BMP header declaring 50000x50000 at 8 bpp, no pixels (54) | core.exception.OutOfMemoryError |
PngSuite ibasn6a08.png (Adam7 interlaced, 339) | core.exception.ArrayIndexError: index 4096 out of bounds for length 4096 |
small.jpg cut to its first 300 of 535 bytes | core.exception.AssertError at jpeg.d(710) in huff_decode |
| BMP cut to 80 of 822 bytes, read by filename | a 16x16 image, no error; the same bytes through readBmp(bytes) throw "out of bmp data" |
The last row is readBmp(string) ignoring fread's result (bmp.d) where the memory overload checks (bmp.d). Errors are therefore reported four ways: Exception, null (JPEG, SVG), a global (lastJpegError), and Error subclasses (OutOfMemoryError, ArrayIndexError, AssertError) that the decoders' catch (Exception) blocks do not catch. The interlaced and truncated cases are bounds-checked failures only because the demo kept bounds checks and assertions; the decoders are @system, so a -release build removes the checks that caught them (see the build types rule). The C seam has a defect of the kind the Sparkles guidelines warn about: for a filename of 512 bytes or more, readJpeg mallocs a buffer and passes it to fopen without copying the name into it (jpeg.d; the same pattern appears in detect_jpeg_image_from_file and decompress_jpeg_image_from_file, jpeg.d, verified to throw Exception("cannot open file …") on a valid JPEG at a 551-byte relative path). No fuzzing harness exists in the repository. Compare hostile input and the Limits budget in image-rs.
6. Allocation and ownership
Pixel storage is GC memory owned by the image object; codec scratch is malloc (PNG's zlib stream and line buffers, the whole JPEG decoder, NanoSVG). clearInternal lets a caller return pixel memory early, with the warning "IF YOU HAVE *ANY* QUESTIONS REGARDING THIS COMMENT, DON'T USE THIS!" (color.d); readJpegFromStream calls it on failure. TrueColorImage(w, h, ubyte[] data) adopts a caller's buffer without copying (color.d), the one zero-copy entry point. loadImageFromFile reads into a GC buffer and frees it with GC.free after decoding (image.d). Native simpledisplay.Image objects hold OS resources and rely on destroy or a GC finalizer. readSvg never frees its rasterizer (image.d).
7. CPU parallelism and SIMD
Not applicable to multithreading or vector intrinsics, because the image modules and decoders are single-threaded scalar code with no worker pool, core.simd or intel-intrinsics use. The one packed-integer trick in the inspected modules is Color.alphaBlend on LittleEndian, which mixes in ColorBlendMixinStr to blend red and blue together inside one uint under the 0xff00ff mask (color.d).
8. GPU offload and interop
No GPU path in the image modules. The only GPU consumer read, arsd.game's OpenGlTexture.bindFrom, uploads GL_RGBA/GL_UNSIGNED_BYTE with glTexImage2D, padding to powers of two; its comment says the padding "will be initialized to zeros automatically", but the buffer comes from malloc, which does not zero (game.d). arsd.dds decodes DXT1/3/5 to RGBA on the CPU rather than handing blocks to the GPU (per the ImageFileFormat.Dds comment, image.d).
9. Temporal, animation and containers
arsd.apng models an animation as ApngAnimation (header, palette, ApngFrame[]), each frame wrapping a TrueColorImage or IndexedImage plus its fcTL fields, and ApngRenderBuffer.nextFrame composites frames into one buffer and returns the delay in milliseconds (apng.d). Its header warns "this interface is not exactly stable" (apng.d). GIF is detected but not decoded.
10. Testing and conformance
png.d, jpeg.d, bmp.d, image.d, svg.d, targa.d, pcx.d, dds.d and imageresize.d contain no unittest block; color.d has one, for colour string parsing, and apng.d's two unittest blocks are version(Demo) examples rather than assertions (apng.d). There is no corpus, no oracle and no CI job over images in the repository. The results above came from PngSuite, which the project does not run.
Lessons for Sparkles
- Q1 A single fixed RGBA8 buffer covers the common "load a picture and show it" case with very little API, and
arsdshows how far that goes: 16-bit precision, colour keys, interlace and colour space are all lost at the boundary. Sparkles' existingsparkles.ui.pngalready shares this shape (see the baseline);arsdis evidence of where that shape stops. - Q1 No stride means no views: every crop, rotation and native-format conversion copies. A Sparkles image type that carries a stride from the start avoids that; one that copies
arsd'scolorsreinterpretation (cast(inout(Color)[]) bytes) gets a cheap typed view of a byte buffer, which transfers directly. - Q2 Runtime polymorphism (
MemoryImagepluscast) made the decoders independent of one another and of the windowing code. That decoupling transfers; the cost is a virtualgetPixelper pixel and conversion toTrueColorImagebefore anything useful happens. - Q4 Optional coupling by
static if (__traits(compiles, { import … }))let each codec stand alone and still speak the shared type. Sparkles achieves the same with sub-packages and should not need the probe, but the idea of a codec that depends only on a tiny core module is thegamut-style split this catalog keeps finding. - Q4 Two readers for one format (eager without CRC, lazy with CRC but without interlace) drifted apart inside one file. A Sparkles format should have one decoder core with eager and incremental fronts over it.
- Q5 Even a minimal model needs to keep what the file says about alpha and transfer:
arsddropstRNSkeys and blends in gamma space with a warning comment. The minimum Sparkles colour model is at least "straight or premultiplied" and "sRGB-encoded or linear" as data on the image. - Q6
TrueColorImage(w, h, data)adopting a buffer, andsimpledisplaywriting straight into a native bitmap, are the two placesarsdavoids copies; a Sparkles upload path wants the same adopt-and-borrow pair, with ownership in the type rather than in a comment. - Q8 Every hostile-input failure verified here (allocation before validation, unchecked CRC, sniffing that turns HTML into an image, assertions reachable from input, ignored
freadresults, an unterminated C string) is cheap to find with PngSuite and a few hand-made headers. That argues for a Sparkles conformance corpus and an allocation budget from the first decoder, not after it. - Q8 Reporting errors by
Exception,null, a global andErrorat once makes a caller's error handling incomplete by construction. Sparkles'Expected-based convention addresses exactly this. - Q9
color_base(types, interface, transforms) separate from per-codec sub-packages (png,jpeg,bmp,svg,ico) and a facade sub-package (image_files, which also bundlestarga.d,pcx.danddds.d,dub.json) is a working D precedent for an image-core and formats split; its weakness is that the facade's format list is closed.
Strengths
- Small, readable API: one colour type, one interface, load and save in one call per format.
- No dependency outside the repository;
arsd.coloravoids Phobos; the main codecs (png,jpeg,bmp,svg,ico) are their own dub sub-packages (dub.json). - Read and write for PNG, JPEG and BMP; SVG rasterization; EXIF orientation applied by default.
- A lazy, range-based PNG reader that checks CRCs and streams scanlines through zlib.
- Direct, well-documented path from a decoded image to a native window bitmap on X11 and Windows.
Weaknesses
- One pixel format; 16-bit, colour keys for non-indexed PNGs, interlaced PNG and all colour metadata are lost or unsupported (verified).
- No resource limits for PNG and BMP; allocation precedes validation (verified).
- Eager PNG path skips CRCs; content sniffing accepts any
<-prefixed buffer as SVG (verified). - Four error channels, including
Errorsubclasses reachable from input (verified). @systemdecoders whose remaining checks are assertions and bounds checks that-releaseremoves.- Almost no tests; no corpus or oracle.
- Since 2024 the code targets OpenD; with DMD 2.112.1
core.dneeds a one-line change to compile (verified).
Key design decisions and trade-offs
| Decision | Rationale | Trade-off |
|---|---|---|
One MemoryImage interface with TrueColorImage and IndexedImage | Keeps the common loader and windowing surface small (color.d) | Virtual per-pixel access; 16-bit samples, non-indexed tRNS keys and colour space are dropped |
| Tightly packed RGBA8 buffer with no explicit stride | Simple ubyte[] / Color[] reinterpretation (color.d) | No zero-copy sub-image views or padded rows |
Optional module coupling via __traits(compiles, { import … }) | Single-file codec modules work alone or with arsd.color / arsd.image (jpeg.d) | Feature surface depends on which files are compiled together |
| Separate eager and range-based PNG chunk readers | pngFromBytes streams chunks and verifies CRCs (png.d) | readPng skips CRCs and LazyPngFile does not implement Adam7 interlace (png.d) |
Closed ImageFileFormat enum and final switch in arsd.image | One-call format sniffing and dispatch (image.d) | Callers cannot register new formats; <-prefix sniffing misclassifies HTML as SVG (image.d) |
Sources
- adamdruppe/arsd at
11491fa8bb9594eb5bd33e2556a9e395d19f30dc:color.d,image.d,png.d,jpeg.d,bmp.d,svg.d,apng.d,targa.d,pcx.d,dds.d,imageresize.d,game.d,simpledisplay.d,dub.json,README.md. - libpng's copy of PngSuite (
contrib/pngsuite) from the Sparkles flake inputlibpng-src, for the verified PNG cases. - Related pages: concepts, Go
image, image-rs,ae.utils.graphics, Dplug graphics, gamut, existing Sparkles image code.