|
| 1 | +use image::imageops::FilterType; |
| 2 | +use image::ImageFormat; |
| 3 | +use std::fmt; |
| 4 | +use std::fs::File; |
| 5 | +use std::path::PathBuf; |
| 6 | +use std::time::{Duration, Instant}; |
| 7 | +pub fn scaledown_image() { |
| 8 | + let path = PathBuf::from("assets/food.jpg"); |
| 9 | + let seve_path = PathBuf::from("src/scaledown"); |
| 10 | + let img = image::open(path).unwrap(); |
| 11 | + for &(name, filter) in [ |
| 12 | + ("near", FilterType::Nearest), |
| 13 | + ("tri", FilterType::Triangle), |
| 14 | + ("cmr", FilterType::CatmullRom), |
| 15 | + ("gauss", FilterType::Gaussian), |
| 16 | + ("lcz2", FilterType::Lanczos3), |
| 17 | + ] |
| 18 | + .iter() |
| 19 | + { |
| 20 | + let timer = Instant::now(); |
| 21 | + let scaled = img.resize(800, 800, filter); |
| 22 | + println!("Scaled by {} in {}", name, Elapsed::from(&timer)); |
| 23 | + let path = seve_path.join(format!("test-{}.png", name)); |
| 24 | + let mut output = File::create(path).unwrap(); |
| 25 | + scaled.write_to(&mut output, ImageFormat::Png).unwrap(); |
| 26 | + } |
| 27 | + |
| 28 | + for size in &[400_u32, 600, 800] { |
| 29 | + let timer = Instant::now(); |
| 30 | + let scaled = img.thumbnail(*size, *size); |
| 31 | + println!("Thumbnailed to {} in {}", size, Elapsed::from(&timer)); |
| 32 | + let path = seve_path.join(format!("test-thumb{}.png", size)); |
| 33 | + let mut output = File::create(path).unwrap(); |
| 34 | + scaled.write_to(&mut output, ImageFormat::Png).unwrap(); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +struct Elapsed(Duration); |
| 39 | + |
| 40 | +impl Elapsed { |
| 41 | + fn from(start: &Instant) -> Self { |
| 42 | + Elapsed(start.elapsed()) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl fmt::Display for Elapsed { |
| 47 | + fn fmt(&self, out: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
| 48 | + match (self.0.as_secs(), self.0.subsec_nanos()) { |
| 49 | + (0, n) if n < 1000 => write!(out, "{} ns", n), |
| 50 | + (0, n) if n < 1_000_000 => write!(out, "{} Β΅s", n / 1000), |
| 51 | + (0, n) => write!(out, "{} ms", n / 1_000_000), |
| 52 | + (s, n) if s < 10 => write!(out, "{}.{:02} s", s, n / 10_000_000), |
| 53 | + (s, _) => write!(out, "{} s", s), |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments