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.

56 lines
1.4 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, mode string) (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. 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. return data, bounds.Dx(), bounds.Dy()
  36. }
  37. var buf bytes.Buffer
  38. switch ext {
  39. case ".png":
  40. png.Encode(&buf, dstImage)
  41. case ".jpg", ".jpeg":
  42. jpeg.Encode(&buf, dstImage, nil)
  43. case ".gif":
  44. gif.Encode(&buf, dstImage, nil)
  45. case ".webp":
  46. webp.Encode(&buf, dstImage, &webp.Options{Quality: 70})
  47. }
  48. return buf.Bytes(), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
  49. } else {
  50. glog.Error(err)
  51. }
  52. return data, 0, 0
  53. }