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