You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.1 KiB

  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) (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. if width == height && bounds.Dx() != bounds.Dy() {
  21. dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
  22. w, h = width, height
  23. } else {
  24. dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
  25. }
  26. } else {
  27. return data, bounds.Dx(), bounds.Dy()
  28. }
  29. var buf bytes.Buffer
  30. switch ext {
  31. case ".png":
  32. png.Encode(&buf, dstImage)
  33. case ".jpg", ".jpeg":
  34. jpeg.Encode(&buf, dstImage, nil)
  35. case ".gif":
  36. gif.Encode(&buf, dstImage, nil)
  37. }
  38. return buf.Bytes(), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
  39. } else {
  40. glog.Error(err)
  41. }
  42. return data, 0, 0
  43. }