Skip to content

Commit

Permalink
Simplify preview scaling logic (mattermost#24507)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
turretkeeper and mattermost-build authored Nov 23, 2023
1 parent 0000f1d commit 8dff1ab
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions server/channels/app/imaging/preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
Expand Down

0 comments on commit 8dff1ab

Please sign in to comment.