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

118 lines
4.4 KiB
Plaintext

#! Contains PNG's encoder, which writes an image's pixels exactly, in the least
#! color type and depth that holds them: gray of 1, 2, 4, or 8 bits; gray with
#! alpha; RGB; RGBA; or a palette of up to 256 colors, of 1, 2, 4, or 8 bits.
#! Each row is filtered by whichever of PNG's filters leaves the least to
#! compress, as libpng chooses, and the rows deflated, after an `sRGB` chunk
#! saying the colors are sRGB's.
module image::png;
#! How a PNG is written.
pub struct options {
pub var level: u32 = 6; #! How hard deflate looks for repeats: from 0, which stores the data as it is, to 9.
pub var reduced: bool = true; #! Whether the least color type and depth holding the pixels is written, or RGBA of 8 bits whatever they are.
pub var interlaced: bool = false; #! Whether it's written in Adam7's seven passes, which a reader may show coarse, then finer.
}
#! Writes a PNG.
#! @param picture The image.
#! @param given How to write it.
#! @returns The file's bytes, or `malformed` where the image has no pixels, or
#! other than `width * height * 4` bytes of them.
pub def encode(picture: &image, given: options = options {}): result<vector<u8>, image_error> {
if !image::is_whole(picture) {
return image_error::malformed;
}
if picture.width > 0x7FFFFFFF || picture.height > 0x7FFFFFFF {
return image_error::too_large;
}
var found := colors {};
var head := header_for(picture, given.reduced, &mut found);
head.interlaced = given.interlaced;
# Each pass's rows, each its filter's byte then it, after the last pass's; one
# pass where it's not interlaced.
var raw := vector::<u8>::new();
raw.reserve(inflated_size(&head));
val step := bytes_per_pixel(&head);
val chosen := head.color != indexed && head.depth == 8;
var line := vector::<u8>::new();
var above := vector::<u8>::new();
for pass in 0u..7u {
val x0 := head.interlaced ? pass_x[pass] : 0;
val y0 := head.interlaced ? pass_y[pass] : 0;
val dx := head.interlaced ? pass_dx[pass] : 1;
val dy := head.interlaced ? pass_dy[pass] : 1;
val columns := head.width > x0 ? (head.width - x0 + dx - 1) / dx : 0;
val rows := head.height > y0 ? (head.height - y0 + dy - 1) / dy : 0;
if columns != 0 && rows != 0 {
val row_bytes := row_size(&head, columns);
line.resize(row_bytes);
above.clear();
above.resize(row_bytes);
for row in 0..rows as u64 {
take_row(&head, picture, &found, y0 + row as u32 * dy, x0, dx, columns, line.slice());
filter_row(line.view(), above.view(), step, chosen, &mut raw);
for index in 0..row_bytes {
above[index] = line[index];
}
}
}
if !head.interlaced {
break;
}
}
var out := vector::<u8>::new();
out.extend(signature[:]);
var described: u8[13];
put_big_endian(described[:], 0, head.width);
put_big_endian(described[:], 4, head.height);
described[8] = head.depth as u8;
described[9] = head.color;
described[12] = head.interlaced ? 1 : 0;
chunk(&mut out, "IHDR", described[:]);
# Its colors are sRGB's, as a renderer means them perceptually.
var intent: u8[1];
chunk(&mut out, "sRGB", intent[:]);
if head.color == indexed {
var colors_of := vector::<u8>::new();
var alphas := vector::<u8>::new();
for entry in 0..head.entries as u64 {
colors_of.extend(head.palette[entry * 4:3]);
if head.palette[entry * 4 + 3] != 255 {
alphas.append(head.palette[entry * 4 + 3]);
}
}
chunk(&mut out, "PLTE", colors_of.view());
if !alphas.is_empty {
chunk(&mut out, "tRNS", alphas.view());
}
}
val compressed := deflate(raw.view(), given.level);
chunk(&mut out, "IDAT", compressed.view());
chunk(&mut out, "IEND", described[0:0]);
return move(out);
}
# Appends a chunk: its length, its type, its data, and the CRC of the last two.
def chunk(out: &mut vector<u8>, kind: strview, data: span<u8>): void {
val start := out.length;
out.resize(start + 4);
put_big_endian(out.slice(), start, data.length as u32);
out.extend(kind);
out.extend(data);
val crc := crc32(out.view()[start + 4:4 + data.length]);
val end := out.length;
out.resize(end + 4);
put_big_endian(out.slice(), end, crc);
}
def put_big_endian(bytes: slice<u8>, at: u64, value: u32): void {
bytes[at] = (value >> 24) as u8;
bytes[at + 1] = (value >> 16) as u8;
bytes[at + 2] = (value >> 8) as u8;
bytes[at + 3] = value as u8;
}