From 5e091bf488badf9704a9223b485ac5165eba19b9 Mon Sep 17 00:00:00 2001 From: Nathan Fiedler Date: Wed, 10 Jun 2015 21:27:58 -0700 Subject: [PATCH] Add a fit function to resize an image Given a bounding box defined by the desired width and height, resize the image to fit that box, maintaining the aspect ratio. cargo test passes --- src/lib.rs | 25 +++++++++++++++++++++++++ tests/lib.rs | 14 ++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 6d52b02..610d808 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -113,6 +113,31 @@ impl MagickWand { } } + /// Resize the image to find within the given dimensions, maintaining + /// the current aspect ratio. + pub fn fit(&self, width: usize, height: usize) { + let mut width_ratio = width as f64; + width_ratio /= self.get_image_width() as f64; + let mut height_ratio = height as f64; + height_ratio /= self.get_image_height() as f64; + let new_width: usize; + let new_height: usize; + if width_ratio < height_ratio { + new_width = width; + new_height = (self.get_image_height() as f64 * width_ratio) as usize; + } else { + new_width = (self.get_image_width() as f64 * height_ratio) as usize; + new_height = height; + } + unsafe { + bindings::MagickResetIterator(self.wand); + while bindings::MagickNextImage(self.wand) != bindings::MagickFalse { + bindings::MagickResizeImage(self.wand, new_width as size_t, new_height as size_t, + FilterType::LanczosFilter as c_uint, 1.0); + } + } + } + /// Write the current image to the provided path. pub fn write_image(&self, path: &str) -> Result<(), &'static str> { let c_name = CString::new(path).unwrap(); diff --git a/tests/lib.rs b/tests/lib.rs index 94245b4..87aa4af 100644 --- a/tests/lib.rs +++ b/tests/lib.rs @@ -97,3 +97,17 @@ fn test_write_to_blob() { assert_eq!(512, wand.get_image_width()); assert_eq!(384, wand.get_image_height()); } + +#[test] +fn test_fit() { + START.call_once(|| { + magick_wand_genesis(); + }); + let wand = MagickWand::new(); + assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok()); + assert_eq!(512, wand.get_image_width()); + assert_eq!(384, wand.get_image_height()); + wand.fit(240, 240); + assert_eq!(240, wand.get_image_width()); + assert_eq!(180, wand.get_image_height()); +}