cropping.go 946 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. )
  12. func Cropped(ext string, read io.ReadSeeker, x1, y1, x2, y2 int) (cropped io.ReadSeeker, err error) {
  13. srcImage, _, err := image.Decode(read)
  14. if err != nil {
  15. glog.Error(err)
  16. return read, err
  17. }
  18. bounds := srcImage.Bounds()
  19. if x2 > bounds.Dx() || y2 > bounds.Dy() {
  20. read.Seek(0, 0)
  21. return read, nil
  22. }
  23. rectangle := image.Rect(x1, y1, x2, y2)
  24. dstImage := imaging.Crop(srcImage, rectangle)
  25. var buf bytes.Buffer
  26. switch ext {
  27. case ".jpg", ".jpeg":
  28. if err = jpeg.Encode(&buf, dstImage, nil); err != nil {
  29. glog.Error(err)
  30. }
  31. case ".png":
  32. if err = png.Encode(&buf, dstImage); err != nil {
  33. glog.Error(err)
  34. }
  35. case ".gif":
  36. if err = gif.Encode(&buf, dstImage, nil); err != nil {
  37. glog.Error(err)
  38. }
  39. }
  40. return bytes.NewReader(buf.Bytes()), err
  41. }