From 61711d202334a7f66ab209d6758a6a59d567c4a4 Mon Sep 17 00:00:00 2001 From: Marco Bonaventura Date: Wed, 26 Feb 2025 10:55:47 +0000 Subject: [PATCH] - Add an example file where we can pass a relative file path as an argument. --- examples/convert_by_args.rs | 65 +++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 examples/convert_by_args.rs diff --git a/examples/convert_by_args.rs b/examples/convert_by_args.rs new file mode 100644 index 0000000..d979dae --- /dev/null +++ b/examples/convert_by_args.rs @@ -0,0 +1,65 @@ +use image::*; +use std::{env::args, fmt::format, path::Path}; +use webp::*; + + +/// cargo run --example convert_by_args lake.jpg. +fn main() { + + //Add a get args functions + let arg: Vec = args().collect(); + if arg.len() != 2 { + eprintln!("Usage: command "); + return; + } + + //Add a format functions for a new Path by String + let path = format(format_args!("assets/{}", arg[1])); + let path = Path::new(&path); + + + // Using `image` crate, open the included .jpg file + let img = image::open(path).unwrap(); + let (w, h) = img.dimensions(); + // Optionally, resize the existing photo and convert back into DynamicImage + let size_factor = 1.0; + let img: DynamicImage = image::DynamicImage::ImageRgba8(imageops::resize( + &img, + (w as f64 * size_factor) as u32, + (h as f64 * size_factor) as u32, + imageops::FilterType::Triangle, + )); + + // Create the WebP encoder for the above image + let encoder: Encoder = Encoder::from_image(&img).unwrap(); + // Encode the image at a specified quality 0-100 + let webp: WebPMemory = encoder.encode(90f32); + // Define and write the WebP-encoded file to a given path + let output_path = Path::new("assets").join("lake").with_extension("webp"); + std::fs::write(&output_path, &*webp).unwrap(); +} + +#[test] +fn test_convert() { + let path = format(format_args!("assets/{}", "lake.jpg")); + let path = Path::new(&path); + // Using `image` crate, open the included .jpg file + let img = image::open(path).unwrap(); + let (w, h) = img.dimensions(); + // Optionally, resize the existing photo and convert back into DynamicImage + let size_factor = 1.0; + let img: DynamicImage = image::DynamicImage::ImageRgba8(imageops::resize( + &img, + (w as f64 * size_factor) as u32, + (h as f64 * size_factor) as u32, + imageops::FilterType::Triangle, + )); + + // Create the WebP encoder for the above image + let encoder: Encoder = Encoder::from_image(&img).unwrap(); + // Encode the image at a specified quality 0-100 + let webp: WebPMemory = encoder.encode(90f32); + // Define and write the WebP-encoded file to a given path + let output_path = Path::new("assets").join("lake").with_extension("webp"); + std::fs::write(&output_path, &*webp).unwrap(); +} \ No newline at end of file