image_optimizer/optimization/
webp_optimizer.rs

1use anyhow::Result;
2use image::DynamicImage;
3use std::fs;
4use std::path::Path;
5
6use crate::cli::Cli;
7
8/// Optimizes a WebP image with configurable quality and lossless options.
9///
10/// This function uses Google's WebP encoder to create optimized WebP images.
11/// It supports both lossy compression with quality control and lossless compression
12/// mode for maximum quality preservation.
13///
14/// # Arguments
15///
16/// * `input_path` - Path to the source WebP file
17/// * `output_path` - Path where the optimized WebP will be written
18/// * `args` - CLI configuration containing quality settings and lossless flag
19/// * `resized_img` - Optional pre-resized image data; if None, reads from `input_path`
20///
21/// # Returns
22///
23/// Returns `Ok(())` on successful optimization.
24///
25/// # Errors
26///
27/// Returns an error if:
28/// - WebP encoding fails
29/// - File I/O operations fail (reading input or writing output)
30/// - Image format conversion to RGB8 fails
31pub fn optimize_webp(
32    input_path: &Path,
33    output_path: &Path,
34    args: &Cli,
35    resized_img: Option<DynamicImage>,
36) -> Result<()> {
37    let rgb_img = if let Some(img) = resized_img {
38        img.to_rgb8()
39    } else {
40        image::open(input_path)?.to_rgb8()
41    };
42
43    let encoder = if args.webp_lossless {
44        webp::Encoder::from_rgb(&rgb_img, rgb_img.width(), rgb_img.height()).encode_lossless()
45    } else {
46        webp::Encoder::from_rgb(&rgb_img, rgb_img.width(), rgb_img.height())
47            .encode(f32::from(args.jpeg_quality))
48    };
49
50    fs::write(output_path, &*encoder)?;
51
52    Ok(())
53}