From 8dff1ab906d2926a6528caca4cfc127d054ce578 Mon Sep 17 00:00:00 2001 From: Turretkeeper <111332069+turretkeeper@users.noreply.github.com> Date: Thu, 23 Nov 2023 13:27:20 -0500 Subject: [PATCH] Simplify preview scaling logic (#24507) * Update preview.go Was some complex logic in there. This should be simpler. * Update preview.go Make GenerateThumbnail code more verbose * Update preview.go Finish renaming targetHeight and targetWidth --------- Co-authored-by: Mattermost Build --- server/channels/app/imaging/preview.go | 31 +++++++++++++------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/server/channels/app/imaging/preview.go b/server/channels/app/imaging/preview.go index 83cf246db5..0159921c79 100644 --- a/server/channels/app/imaging/preview.go +++ b/server/channels/app/imaging/preview.go @@ -25,29 +25,28 @@ func GeneratePreview(img image.Image, width int) image.Image { } // GenerateThumbnail generates the thumbnail for the given image. -func GenerateThumbnail(img image.Image, width, height int) image.Image { +func GenerateThumbnail(img image.Image, targetWidth, targetHeight int) image.Image { thumb := img - w := img.Bounds().Dx() - h := img.Bounds().Dy() - expectedRatio := float64(height) / float64(width) + width := img.Bounds().Dx() + height := img.Bounds().Dy() + expectedRatio := float64(targetHeight) / float64(targetWidth) - if h > height || w > width { - ratio := float64(h) / float64(w) + // If both dimensions are over the target size, we scale down until one is not. + // If one dimension is over the target size, we scale down until both are not. + // If neither dimension is over the target size, we return the image as is. + if height > targetHeight || width > targetWidth { + ratio := float64(height) / float64(width) if ratio < expectedRatio { - // we pre-calculate the thumbnail's width to make sure we are not upscaling. - targetWidth := int(float64(height) * float64(w) / float64(h)) - if targetWidth <= w { - thumb = imaging.Resize(img, 0, height, imaging.Lanczos) + if height >= targetHeight { + thumb = imaging.Resize(img, 0, targetHeight, imaging.Lanczos) } else { - thumb = imaging.Resize(img, width, 0, imaging.Lanczos) + thumb = imaging.Resize(img, targetWidth, 0, imaging.Lanczos) } } else { - // we pre-calculate the thumbnail's height to make sure we are not upscaling. - targetHeight := int(float64(width) * float64(h) / float64(w)) - if targetHeight <= h { - thumb = imaging.Resize(img, width, 0, imaging.Lanczos) + if width >= targetWidth { + thumb = imaging.Resize(img, targetWidth, 0, imaging.Lanczos) } else { - thumb = imaging.Resize(img, 0, height, imaging.Lanczos) + thumb = imaging.Resize(img, 0, targetHeight, imaging.Lanczos) } } }