Skip to main content

clairlune_render/
encode.rs

1//! PNG export. Scenes have at most 255 colours, so stills are written as indexed
2//! (paletted) PNGs, which are much smaller than RGBA.
3
4use crate::IndexedImage;
5use crate::palette::IndexedPalette;
6use std::fs::File;
7use std::io::{self, BufWriter, Write};
8use std::path::Path;
9
10/// Writes an indexed PNG.
11pub fn encode_png<W: Write>(
12    img: &IndexedImage,
13    palette: &IndexedPalette,
14    out: W,
15) -> Result<(), png::EncodingError> {
16    let mut enc = png::Encoder::new(out, img.width, img.height);
17    enc.set_color(png::ColorType::Indexed);
18    enc.set_depth(png::BitDepth::Eight);
19    enc.set_palette(palette.rgb_bytes());
20    enc.set_compression(png::Compression::Balanced);
21    enc.set_filter(png::Filter::Adaptive);
22    let mut writer = enc.write_header()?;
23    writer.write_image_data(&img.pixels)?;
24    writer.finish()
25}
26
27/// Writes an indexed PNG to a file.
28pub fn save_png(path: &Path, img: &IndexedImage, palette: &IndexedPalette) -> io::Result<()> {
29    let file = BufWriter::new(File::create(path)?);
30    encode_png(img, palette, file).map_err(io::Error::other)
31}
32
33/// Expands palette indices to RGBA8 (for tests, previews and GPU upload).
34pub fn to_rgba(img: &IndexedImage, palette: &IndexedPalette) -> Vec<u8> {
35    let colors = palette.colors();
36    let mut out = Vec::with_capacity(img.pixels.len() * 4);
37    for &i in &img.pixels {
38        let c = colors[i as usize];
39        out.extend_from_slice(&[c.r, c.g, c.b, 255]);
40    }
41    out
42}