resizing.go 1.4 KB

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