use std::fs::File;
use std::io::BufWriter;
use std::path::Path;
use crate::CaptureError;
use crate::image::{Image, unpremultiply};
pub fn write_png(image: &Image, path: impl AsRef<Path>) -> Result<(), CaptureError> {
if image.is_empty() {
return Err(CaptureError::EmptyImage);
}
let mut rgba = Vec::with_capacity(image.pixels().len() * 4);
for pixel in image.pixels() {
rgba.extend_from_slice(&unpremultiply(*pixel));
}
let file = File::create(path).map_err(CaptureError::Io)?;
let mut encoder = png::Encoder::new(BufWriter::new(file), image.width(), image.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().map_err(png_io)?;
writer.write_image_data(&rgba).map_err(png_io)?;
writer.finish().map_err(png_io)
}
fn png_io(error: png::EncodingError) -> CaptureError {
match error {
png::EncodingError::IoError(io) => CaptureError::Io(io),
other => CaptureError::Io(std::io::Error::other(other.to_string())),
}
}