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
This commit is contained in:
parent
56877aaad3
commit
5e091bf488
25
src/lib.rs
25
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.
|
/// Write the current image to the provided path.
|
||||||
pub fn write_image(&self, path: &str) -> Result<(), &'static str> {
|
pub fn write_image(&self, path: &str) -> Result<(), &'static str> {
|
||||||
let c_name = CString::new(path).unwrap();
|
let c_name = CString::new(path).unwrap();
|
||||||
|
|
14
tests/lib.rs
14
tests/lib.rs
|
@ -97,3 +97,17 @@ fn test_write_to_blob() {
|
||||||
assert_eq!(512, wand.get_image_width());
|
assert_eq!(512, wand.get_image_width());
|
||||||
assert_eq!(384, wand.get_image_height());
|
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());
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue