Update write_png() to take a Color array

This commit is contained in:
Josh Holtrop 2023-10-10 19:25:24 -04:00
parent 8c109a741b
commit f8fc3518dd

View File

@ -7,6 +7,7 @@ import std.digest;
import fart.bfile;
import fart.crc32;
import fart.hton;
import fart.color;
private immutable ubyte[] HEADER = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
@ -88,13 +89,27 @@ private void write_chunk(Chunk)(BFile file, string chunk_type, Chunk chunk)
file.writeObject(crc_be32);
}
public void write_png(string filename, uint width, uint height, ubyte[] data)
public void write_png(string filename, uint width, uint height, const(Color)[] data)
{
if (data.length != width * height)
return;
ubyte[] pixel_data;
size_t data_index;
for (size_t y = 0; y < height; y++)
{
/* Filter method 0 (None) */
pixel_data ~= 0;
for (size_t x = 0; x < width; x++)
{
pixel_data ~= data[data_index++].rgba32();
}
}
BFile file = BFile(filename);
file.write(HEADER);
IHDR ihdr = IHDR(width, height);
write_chunk(file, "IHDR", ihdr);
IDAT idat = IDAT(data);
IDAT idat = IDAT(pixel_data);
write_chunk(file, "IDAT", idat);
IEND iend;
write_chunk(file, "IEND", iend);
@ -103,18 +118,16 @@ public void write_png(string filename, uint width, uint height, ubyte[] data)
void png_test()
{
ubyte[] pixel_data = [];
Color[] pixel_data = [];
for (size_t y = 0; y < 500; y++)
{
/* Filter method 0 (None) */
pixel_data ~= [0];
for (size_t x = 0; x < 500; x++)
{
ubyte r = cast(ubyte)(x / 2);
ubyte g = 0x80;
ubyte b = cast(ubyte)((500 - y) / 2);
ubyte a = cast(ubyte)((abs(cast(int)x - 250) + abs(cast(int)y - 250)) / 2);
pixel_data ~= [r, g, b, a];
pixel_data ~= Color(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
}
}
write_png("out.png", 500, 500, pixel_data);