# HG changeset patch # User Emmanuel Gil Peyrot # Date 1641914721 -3600 # Node ID 1a362692ed76cba066eac6ced833d3b168e9748e # Parent 9b4be43ea74f31afade930c893326a4c0cd1ff2f Add native support for stdin/stdout. diff --git a/src/main.rs b/src/main.rs --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,9 @@ -use image::{imageops::FilterType, io::Reader as ImageReader}; +use image::{imageops::FilterType, GenericImageView}; use log::info; use std::env; use std::error::Error; +use std::fs::File; +use std::io::{self, BufReader, Read}; use std::path::Path; use std::str::FromStr; @@ -12,32 +14,39 @@ fn main() -> Result<(), Box> 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(()); + let mut input = Vec::new(); + if args[2] == "-" { + io::stdin().read_to_end(&mut input)?; + } else { + let file = File::open(&args[2])?; + let mut reader = BufReader::new(file); + reader.read_to_end(&mut input)?; } - // Open the image file. - let reader = ImageReader::open(input)?; + let output = if args[3] == "-" { + Path::new("/dev/stdout") + } else { + Path::new(&args[3]) + }; + + // Guess the format of the input file. + let format = image::guess_format(&input)?; - // Extract the guessed format, or panic if unknown/unsupported. - let format = reader.format().expect("Unsupported format in input file"); + // Decode the image file. + let image = image::load_from_memory(&input)?; - // Decode the image. - let image = reader.decode()?; + let (mut width, mut height) = image.dimensions(); + if width > size { + width = size; + } + if height > size { + height = size; + } // Resize it to the requested size. - let image = image.resize(size, size, FilterType::Triangle); + let image = image.resize(width, height, FilterType::Triangle); // Then save it to the output. image.save_with_format(output, format)?;