image icon indicating copy to clipboard operation
image copied to clipboard

How to resize an image with padding

Open samdenty opened this issue 3 years ago • 3 comments

I'm trying to create a thumbnail that preserves the aspect ratio, like resize_to_fill but instead of cropping it, padding is used instead

samdenty avatar Apr 15 '22 17:04 samdenty

let max_width = 1024;
let max_height = 1024;
let mut width = img.width();
let mut height = img.height();
let aspect_ratio = (width as f32) / (height as f32);

if width > max_width || height < max_height {
  width = max_width;
  height = ((width as f32) / aspect_ratio) as u32;
}

if height > max_height || width < max_width {
  height = max_height;
  width = ((height as f32) * aspect_ratio) as u32;
}

let thumbnail = img.resize_exact(width, height, FilterType::Nearest);
let mut img = ImageBuffer::from_fn(max_width, max_height, |_x, _y| image::Rgba([0, 0, 0, 0]));
image::imageops::overlay(
  &mut img,
  &thumbnail,
  (max_width - i64::from(width)) / 2,
  (max_height - i64::from(height)) / 2,
);

samdenty avatar Apr 15 '22 18:04 samdenty

Maybe we make the above snippet DynamicImage::resize_padded

samdenty avatar Apr 15 '22 18:04 samdenty

I would like this as well.

Zerowalker avatar Oct 26 '23 11:10 Zerowalker