image
image copied to clipboard
How to resize an image with padding
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
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,
);
Maybe we make the above snippet DynamicImage::resize_padded
I would like this as well.