Files
image/image/image.sakura
T
2026-10-28 08:29:27 -05:00

64 lines
2.8 KiB
Plaintext

#! Contains `image`, pixels read from PNG, JPEG, or SVG, or written to PNG or
#! JPEG, and why one couldn't be.
#!
#! Each format is a module of its own beneath this one, `image::png`,
#! `image::jpeg`, and `image::svg`, which this one's functions choose between:
#! by the bytes' first few to read them, and by the format asked for, or a
#! file's extension, to write them. Each gives and takes the same `image`: RGBA,
#! eight bits a channel, in sRGB, its alpha straight rather than premultiplied,
#! its rows from the top, which is what a GPU takes as `rgba8_srgb`.
module image;
#! The most pixels an image may have: 64 M, or 256 MiB of RGBA. One said to have
#! more is refused before its pixels are read, as `too_large`.
pub const max_pixels: u64 = 0x4000000;
#! Why an image could not be read or written.
pub enum image_error: u8 {
unreadable, #! The file could not be read.
unwritable, #! The file, or the stream, could not be written.
unrecognized, #! The bytes are none of the formats read, PNG, JPEG, or SVG, or a file's extension none of those written.
malformed, #! The data breaks its format, or is cut short; or an image written has no pixels, or other than `width * height * 4` bytes of them.
unsupported, #! The data is well formed, but uses what isn't read, as JPEG's arithmetic coding; or the format isn't written, as SVG isn't.
too_large, #! The image has more pixels than `max_pixels`, or is wider or taller than its format holds.
}
#! Pixels: RGBA, eight bits a channel, in sRGB, with straight alpha, a row of
#! `width` after another from the top.
pub struct image {
pub var width: u32;
pub var height: u32;
pub var pixels: vector<u8>; #! `width * height * 4` bytes.
}
#! The color of a pixel.
#! @param this The image.
#! @param x The column, from the left, below `width`.
#! @param y The row, from the top, below `height`.
#! @returns Its red, green, blue, and alpha.
pub def image::at(&this, x: u32, y: u32): u8[4] {
val start := ((y as u64) * (this.width as u64) + (x as u64)) * 4;
return [this.pixels[start], this.pixels[start + 1], this.pixels[start + 2], this.pixels[start + 3]];
}
# An image of a size, every pixel clear, or `too_large` where it has more pixels
# than may be.
def blank(width: u32, height: u32): result<image, image_error> {
val count := (width as u64) * (height as u64);
if count > max_pixels {
return image_error::too_large;
}
var pixels := vector::<u8>::new();
pixels.resize(count * 4);
return image { width = width, height = height, pixels = move(pixels) };
}
# Whether an image is whole, as writing it needs: it has pixels, and as many
# bytes of them as its size says.
def is_whole(picture: &image): bool {
return picture.width != 0 && picture.height != 0
&& picture.pixels.length == (picture.width as u64) * (picture.height as u64) * 4;
}