process.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package main
  2. import (
  3. "math"
  4. "github.com/h2non/bimg"
  5. )
  6. type processingOptions struct {
  7. resize string
  8. width int
  9. height int
  10. gravity bimg.Gravity
  11. enlarge bool
  12. format bimg.ImageType
  13. }
  14. var imageTypes = map[string]bimg.ImageType{
  15. "jpeg": bimg.JPEG,
  16. "jpg": bimg.JPEG,
  17. "png": bimg.PNG,
  18. "webp": bimg.WEBP,
  19. }
  20. var gravityTypes = map[string]bimg.Gravity{
  21. "ce": bimg.GravityCentre,
  22. "no": bimg.GravityNorth,
  23. "ea": bimg.GravityEast,
  24. "so": bimg.GravitySouth,
  25. "we": bimg.GravityWest,
  26. "sm": bimg.GravitySmart,
  27. }
  28. func round(f float64) int {
  29. return int(f + .5)
  30. }
  31. func calcSize(size bimg.ImageSize, po processingOptions) (int, int) {
  32. if (po.width == size.Width && po.height == size.Height) || (po.resize != "fill" && po.resize != "fit") {
  33. return po.width, po.height
  34. }
  35. fsw, fsh, fow, foh := float64(size.Width), float64(size.Height), float64(po.width), float64(po.height)
  36. wr := fow / fsw
  37. hr := foh / fsh
  38. var rate float64
  39. if po.resize == "fit" {
  40. rate = math.Min(wr, hr)
  41. } else {
  42. rate = math.Max(wr, hr)
  43. }
  44. return round(math.Min(fsw*rate, fow)), round(math.Min(fsh*rate, foh))
  45. }
  46. func processImage(p []byte, po processingOptions) ([]byte, error) {
  47. var err error
  48. img := bimg.NewImage(p)
  49. size, err := img.Size()
  50. if err != nil {
  51. return nil, err
  52. }
  53. // Default options
  54. opts := bimg.Options{
  55. Interpolator: bimg.Bicubic,
  56. Quality: conf.Quality,
  57. Gravity: po.gravity,
  58. Enlarge: po.enlarge,
  59. Type: po.format,
  60. }
  61. opts.Width, opts.Height = calcSize(size, po)
  62. switch po.resize {
  63. case "fit":
  64. opts.Embed = true
  65. case "fill":
  66. opts.Embed = true
  67. opts.Crop = true
  68. case "crop":
  69. opts.Crop = true
  70. default:
  71. opts.Force = true
  72. }
  73. return img.Process(opts)
  74. }