resizing.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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/chrislusf/seaweedfs/weed/glog"
  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. read.Seek(0, 0)
  36. return read, bounds.Dx(), bounds.Dy()
  37. }
  38. var buf bytes.Buffer
  39. switch ext {
  40. case ".png":
  41. png.Encode(&buf, dstImage)
  42. case ".jpg", ".jpeg":
  43. jpeg.Encode(&buf, dstImage, nil)
  44. case ".gif":
  45. gif.Encode(&buf, dstImage, nil)
  46. }
  47. return bytes.NewReader(buf.Bytes()), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
  48. } else {
  49. glog.Error(err)
  50. }
  51. return read, 0, 0
  52. }