Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NFT Metadata Crawler] Maintain image aspect ration on resize #9688

Merged
merged 2 commits into from
Aug 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ impl ImageOptimizer {
_ => {
let img = image::load_from_memory(&img_bytes)
.context(format!("Failed to load image from memory: {} bytes", size))?;
let resized_image = resize(&img.to_rgb8(), 400, 400, FilterType::Gaussian);
let (nwidth, nheight) =
Self::calculate_dimensions_with_ration(512, img.width(), img.height());
let resized_image =
resize(&img.to_rgb8(), nwidth, nheight, FilterType::Gaussian);
Ok((Self::to_jpeg_bytes(resized_image, image_quality)?, format))
},
}
Expand All @@ -85,6 +88,23 @@ impl ImageOptimizer {
}
}

/// Calculate new dimensions given a goal size while maintaining original aspect ratio
fn calculate_dimensions_with_ration(goal: u32, width: u32, height: u32) -> (u32, u32) {
if width == 0 || height == 0 {
return (0, 0);
}

if width > height {
let new_width = goal;
let new_height = (goal as f64 * (height as f64 / width as f64)).round() as u32;
(new_width, new_height)
} else {
let new_height = goal;
let new_width = (goal as f64 * (width as f64 / height as f64)).round() as u32;
(new_width, new_height)
}
}

/// Converts image to JPEG bytes vector
fn to_jpeg_bytes(
image_buffer: ImageBuffer<image::Rgb<u8>, Vec<u8>>,
Expand Down