Mercurial > image-resizer
changeset 0:9b4be43ea74f
Hello world!
author | Emmanuel Gil Peyrot <linkmauve@linkmauve.fr> |
---|---|
date | Tue, 11 Jan 2022 16:00:11 +0100 |
parents | |
children | 1a362692ed76 |
files | .hgignore Cargo.toml src/main.rs |
diffstat | 3 files changed, 64 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
new file mode 100644 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "image-resizer" +version = "0.1.0" +edition = "2018" +authors = ["Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>"] +description = "Resizer of PNGs and JPEGs" +homepage = "https://linkmauve.fr/dev/image-resizer" +repository = "https://hg.linkmauve.fr/image-resizer" +keywords = ["image", "resizer", "png", "jpeg"] +license = "MPL-2.0" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +image = { version = "0.23", default-features = false, features = ["png", "jpeg"] } +log = "0.4"
new file mode 100644 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,47 @@ +use image::{imageops::FilterType, io::Reader as ImageReader}; +use log::info; +use std::env; +use std::error::Error; +use std::path::Path; +use std::str::FromStr; + +fn main() -> Result<(), Box<dyn Error>> { + let args: Vec<_> = env::args().collect(); + if args.len() != 4 { + eprintln!("Usage: {} <size> <input> <output>", args[0]); + std::process::exit(1); + } + + // Parse the arguments. + let size = u32::from_str(&args[1])?; + let input = Path::new(&args[2]); + let output = Path::new(&args[3]); + + let (width, height) = image::image_dimensions(input)?; + if width < size && height < size { + info!( + "Input is already smaller than {}×{}, copying as is.", + size, size + ); + std::fs::copy(input, output)?; + return Ok(()); + } + + // Open the image file. + let reader = ImageReader::open(input)?; + + // Extract the guessed format, or panic if unknown/unsupported. + let format = reader.format().expect("Unsupported format in input file"); + + // Decode the image. + let image = reader.decode()?; + + // Resize it to the requested size. + let image = image.resize(size, size, FilterType::Triangle); + + // Then save it to the output. + image.save_with_format(output, format)?; + + info!("Successfully resized!"); + Ok(()) +}