github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/app/imaging/preview.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package imaging 5 6 import ( 7 "bytes" 8 "fmt" 9 "image" 10 "image/jpeg" 11 12 "github.com/disintegration/imaging" 13 ) 14 15 // GeneratePreview generates the preview for the given image. 16 func GeneratePreview(img image.Image, width int) image.Image { 17 preview := img 18 w := img.Bounds().Dx() 19 20 if w > width { 21 preview = imaging.Resize(img, width, 0, imaging.Lanczos) 22 } 23 24 return preview 25 } 26 27 // GenerateThumbnail generates the thumbnail for the given image. 28 func GenerateThumbnail(img image.Image, width, height int) image.Image { 29 thumb := img 30 w := img.Bounds().Dx() 31 h := img.Bounds().Dy() 32 expectedRatio := float64(height) / float64(width) 33 34 if h > height || w > width { 35 ratio := float64(h) / float64(w) 36 if ratio < expectedRatio { 37 // we pre-calculate the thumbnail's width to make sure we are not upscaling. 38 targetWidth := int(float64(height) * float64(w) / float64(h)) 39 if targetWidth <= w { 40 thumb = imaging.Resize(img, 0, height, imaging.Lanczos) 41 } else { 42 thumb = imaging.Resize(img, width, 0, imaging.Lanczos) 43 } 44 } else { 45 // we pre-calculate the thumbnail's height to make sure we are not upscaling. 46 targetHeight := int(float64(width) * float64(h) / float64(w)) 47 if targetHeight <= h { 48 thumb = imaging.Resize(img, width, 0, imaging.Lanczos) 49 } else { 50 thumb = imaging.Resize(img, 0, height, imaging.Lanczos) 51 } 52 } 53 } 54 55 return thumb 56 } 57 58 // GenerateMiniPreviewImage generates the mini preview for the given image. 59 func GenerateMiniPreviewImage(img image.Image, w, h, q int) ([]byte, error) { 60 var buf bytes.Buffer 61 preview := imaging.Resize(img, w, h, imaging.Lanczos) 62 if err := jpeg.Encode(&buf, preview, &jpeg.Options{Quality: q}); err != nil { 63 return nil, fmt.Errorf("failed to encode image to JPEG format: %w", err) 64 } 65 return buf.Bytes(), nil 66 }