perf: allocate a little less often

This commit is contained in:
frozolotl 2024-12-14 01:03:52 +01:00
parent 9789fdb860
commit 60045fab3b

View File

@ -79,7 +79,6 @@ fn build_texture(image: &Image, w: u32, h: u32) -> Option<Arc<sk::Pixmap>> {
}
/// Scale a rastered image to a given size and return texture.
// TODO(frozolotl): optimize pixmap allocation
fn scale_image(
image: &image::DynamicImage,
scaling: ImageScaling,
@ -87,6 +86,11 @@ fn scale_image(
h: u32,
) -> Option<Arc<sk::Pixmap>> {
let mut pixmap = sk::Pixmap::new(w, h)?;
let buf;
let resized = if (w, h) == (image.width(), image.height()) {
// Small optimization to not allocate in case image is not resized.
image
} else {
let upscale = w > image.width();
let filter = match scaling {
ImageScaling::Auto if upscale => FilterType::CatmullRom,
@ -94,8 +98,10 @@ fn scale_image(
ImageScaling::Pixelated => FilterType::Nearest,
_ => FilterType::Lanczos3, // downscale
};
let buf = image.resize(w, h, filter);
for ((_, _, src), dest) in buf.pixels().zip(pixmap.pixels_mut()) {
buf = image.resize(w, h, filter);
&buf
};
for ((_, _, src), dest) in resized.pixels().zip(pixmap.pixels_mut()) {
let Rgba([r, g, b, a]) = src;
*dest = sk::ColorU8::from_rgba(r, g, b, a).premultiply();
}