image_optimizer/optimization/
png_optimizer.rs

1use anyhow::{Context, Result};
2use image::{DynamicImage, ImageFormat};
3use std::fs;
4use std::path::Path;
5
6use crate::cli::Cli;
7
8/// Optimizes a PNG image using oxipng with zopfli compression
9///
10/// # Errors
11/// Returns an error if PNG optimization fails or file I/O operations fail
12pub fn optimize_png(
13    input_path: &Path,
14    output_path: &Path,
15    _args: &Cli,
16    resized_img: Option<DynamicImage>,
17) -> Result<()> {
18    if let Some(img) = resized_img {
19        img.save_with_format(output_path, ImageFormat::Png)?;
20    } else {
21        fs::copy(input_path, output_path)?;
22    }
23
24    let options = oxipng::Options {
25        optimize_alpha: true,
26        strip: oxipng::StripChunks::Safe,
27        ..Default::default()
28    };
29
30    let input_file = oxipng::InFile::Path(output_path.to_path_buf());
31    let output_file = oxipng::OutFile::Path {
32        path: Some(output_path.to_path_buf()),
33        preserve_attrs: true,
34    };
35
36    oxipng::optimize(&input_file, &output_file, &options).context("Failed to optimize PNG")?;
37
38    Ok(())
39}