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.

36 lines
820 B

  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) {
  11. if width == 0 && height == 0 {
  12. return data
  13. }
  14. if srcImage, _, err := image.Decode(bytes.NewReader(data)); err == nil {
  15. bounds := srcImage.Bounds()
  16. var dstImage *image.NRGBA
  17. if width == height && bounds.Dx() != bounds.Dy() {
  18. dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
  19. } else {
  20. dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
  21. }
  22. var buf bytes.Buffer
  23. switch ext {
  24. case ".png":
  25. png.Encode(&buf, dstImage)
  26. case ".jpg":
  27. jpeg.Encode(&buf, dstImage, nil)
  28. case ".gif":
  29. gif.Encode(&buf, dstImage, nil)
  30. }
  31. return buf.Bytes()
  32. }
  33. return data
  34. }