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.

49 lines
1.2 KiB

  1. package images
  2. import (
  3. "bytes"
  4. "image"
  5. "image/gif"
  6. "image/jpeg"
  7. "image/png"
  8. "github.com/chai2010/webp"
  9. "github.com/chrislusf/seaweedfs/weed/glog"
  10. "github.com/disintegration/imaging"
  11. )
  12. func Resized(ext string, data []byte, width, height int) (resized []byte, w int, h int) {
  13. if width == 0 && height == 0 {
  14. return data, 0, 0
  15. }
  16. srcImage, _, err := image.Decode(bytes.NewReader(data))
  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. if width == height && bounds.Dx() != bounds.Dy() {
  22. dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
  23. w, h = width, height
  24. } else {
  25. dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
  26. }
  27. } else {
  28. return data, bounds.Dx(), bounds.Dy()
  29. }
  30. var buf bytes.Buffer
  31. switch ext {
  32. case ".png":
  33. png.Encode(&buf, dstImage)
  34. case ".jpg", ".jpeg":
  35. jpeg.Encode(&buf, dstImage, nil)
  36. case ".gif":
  37. gif.Encode(&buf, dstImage, nil)
  38. case ".webp":
  39. webp.Encode(&buf, dstImage, &webp.Options{Quality: 70})
  40. }
  41. return buf.Bytes(), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
  42. } else {
  43. glog.Error(err)
  44. }
  45. return data, 0, 0
  46. }