resizing.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package images
  2. import (
  3. "bytes"
  4. "image"
  5. "image/gif"
  6. "image/jpeg"
  7. "image/png"
  8. "io"
  9. "github.com/disintegration/imaging"
  10. "github.com/seaweedfs/seaweedfs/weed/glog"
  11. _ "golang.org/x/image/webp"
  12. )
  13. func Resized(ext string, read io.ReadSeeker, width, height int, mode string) (resized io.ReadSeeker, w int, h int) {
  14. if width == 0 && height == 0 {
  15. return read, 0, 0
  16. }
  17. srcImage, _, err := image.Decode(read)
  18. if err == nil {
  19. bounds := srcImage.Bounds()
  20. var dstImage *image.NRGBA
  21. if bounds.Dx() > width && width != 0 || bounds.Dy() > height && height != 0 {
  22. switch mode {
  23. case "fit":
  24. dstImage = imaging.Fit(srcImage, width, height, imaging.Lanczos)
  25. case "fill":
  26. dstImage = imaging.Fill(srcImage, width, height, imaging.Center, imaging.Lanczos)
  27. default:
  28. if width == height && bounds.Dx() != bounds.Dy() {
  29. dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
  30. w, h = width, height
  31. } else {
  32. dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
  33. }
  34. }
  35. } else {
  36. read.Seek(0, 0)
  37. return read, bounds.Dx(), bounds.Dy()
  38. }
  39. var buf bytes.Buffer
  40. switch ext {
  41. case ".png":
  42. png.Encode(&buf, dstImage)
  43. case ".jpg", ".jpeg":
  44. jpeg.Encode(&buf, dstImage, nil)
  45. case ".gif":
  46. gif.Encode(&buf, dstImage, nil)
  47. case ".webp":
  48. // Webp does not have golang encoder.
  49. png.Encode(&buf, dstImage)
  50. }
  51. return bytes.NewReader(buf.Bytes()), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
  52. } else {
  53. glog.Error(err)
  54. }
  55. return read, 0, 0
  56. }