changeset 1:1a362692ed76 default tip

Add native support for stdin/stdout.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Tue, 11 Jan 2022 16:25:21 +0100
parents 9b4be43ea74f
children
files src/main.rs
diffstat 1 files changed, 28 insertions(+), 19 deletions(-) [+]
line wrap: on
line diff
--- 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<dyn Error>> 
         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)?;