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 <build@mattermost.com>
This commit is contained in:
Turretkeeper 2023-11-23 13:27:20 -05:00 committed by GitHub
parent 0000f1d00f
commit 8dff1ab906
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -25,29 +25,28 @@ func GeneratePreview(img image.Image, width int) image.Image {
} }
// GenerateThumbnail generates the thumbnail for the given 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 thumb := img
w := img.Bounds().Dx() width := img.Bounds().Dx()
h := img.Bounds().Dy() height := img.Bounds().Dy()
expectedRatio := float64(height) / float64(width) expectedRatio := float64(targetHeight) / float64(targetWidth)
if h > height || w > width { // If both dimensions are over the target size, we scale down until one is not.
ratio := float64(h) / float64(w) // 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 { if ratio < expectedRatio {
// we pre-calculate the thumbnail's width to make sure we are not upscaling. if height >= targetHeight {
targetWidth := int(float64(height) * float64(w) / float64(h)) thumb = imaging.Resize(img, 0, targetHeight, imaging.Lanczos)
if targetWidth <= w {
thumb = imaging.Resize(img, 0, height, imaging.Lanczos)
} else { } else {
thumb = imaging.Resize(img, width, 0, imaging.Lanczos) thumb = imaging.Resize(img, targetWidth, 0, imaging.Lanczos)
} }
} else { } else {
// we pre-calculate the thumbnail's height to make sure we are not upscaling. if width >= targetWidth {
targetHeight := int(float64(width) * float64(h) / float64(w)) thumb = imaging.Resize(img, targetWidth, 0, imaging.Lanczos)
if targetHeight <= h {
thumb = imaging.Resize(img, width, 0, imaging.Lanczos)
} else { } else {
thumb = imaging.Resize(img, 0, height, imaging.Lanczos) thumb = imaging.Resize(img, 0, targetHeight, imaging.Lanczos)
} }
} }
} }