You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.0 KiB

  1. package images
  2. import (
  3. "bytes"
  4. "github.com/disintegration/imaging"
  5. "image"
  6. "image/gif"
  7. "image/jpeg"
  8. "image/png"
  9. )
  10. func Resized(ext string, data []byte, width, height int) (resized []byte, w int, h int) {
  11. if width == 0 && height == 0 {
  12. return data, 0, 0
  13. }
  14. if srcImage, _, err := image.Decode(bytes.NewReader(data)); err == nil {
  15. bounds := srcImage.Bounds()
  16. var dstImage *image.NRGBA
  17. if bounds.Dx() > width && width != 0 || bounds.Dy() > height && height != 0 {
  18. if width == height && bounds.Dx() != bounds.Dy() {
  19. dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
  20. w, h = width, height
  21. } else {
  22. dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
  23. }
  24. } else {
  25. return data, bounds.Dx(), bounds.Dy()
  26. }
  27. var buf bytes.Buffer
  28. switch ext {
  29. case ".png":
  30. png.Encode(&buf, dstImage)
  31. case ".jpg", ".jpeg":
  32. jpeg.Encode(&buf, dstImage, nil)
  33. case ".gif":
  34. gif.Encode(&buf, dstImage, nil)
  35. }
  36. return buf.Bytes(), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
  37. }
  38. return data, 0, 0
  39. }