resizing.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. )
  11. func Resized(ext string, data []byte, width, height int, mode string) (resized []byte, w int, h int) {
  12. if width == 0 && height == 0 {
  13. return data, 0, 0
  14. }
  15. srcImage, _, err := image.Decode(bytes.NewReader(data))
  16. if err == nil {
  17. bounds := srcImage.Bounds()
  18. var dstImage *image.NRGBA
  19. if bounds.Dx() > width && width != 0 || bounds.Dy() > height && height != 0 {
  20. switch mode {
  21. case "fit":
  22. dstImage = imaging.Fit(srcImage, width, height, imaging.Lanczos)
  23. case "fill":
  24. dstImage = imaging.Fill(srcImage, width, height, imaging.Center, imaging.Lanczos)
  25. default:
  26. if width == height && bounds.Dx() != bounds.Dy() {
  27. dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
  28. w, h = width, height
  29. } else {
  30. dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
  31. }
  32. }
  33. } else {
  34. return data, bounds.Dx(), bounds.Dy()
  35. }
  36. var buf bytes.Buffer
  37. switch ext {
  38. case ".png":
  39. png.Encode(&buf, dstImage)
  40. case ".jpg", ".jpeg":
  41. jpeg.Encode(&buf, dstImage, nil)
  42. case ".gif":
  43. gif.Encode(&buf, dstImage, nil)
  44. }
  45. return buf.Bytes(), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
  46. } else {
  47. glog.Error(err)
  48. }
  49. return data, 0, 0
  50. }