view src/main.rs @ 0:9b4be43ea74f

Hello world!
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Tue, 11 Jan 2022 16:00:11 +0100
parents
children 1a362692ed76
line wrap: on
line source

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(())
}