process.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. }
  19. var gravityTypes = map[string]bimg.Gravity{
  20. "ce": bimg.GravityCentre,
  21. "no": bimg.GravityNorth,
  22. "ea": bimg.GravityEast,
  23. "so": bimg.GravitySouth,
  24. "we": bimg.GravityWest,
  25. "sm": bimg.GravitySmart,
  26. }
  27. func round(f float64) int {
  28. return int(f + .5)
  29. }
  30. func calcSize(size bimg.ImageSize, po processingOptions) (int, int) {
  31. if (po.width == size.Width && po.height == size.Height) || (po.resize != "fill" && po.resize != "fit") {
  32. return po.width, po.height
  33. }
  34. fsw, fsh, fow, foh := float64(size.Width), float64(size.Height), float64(po.width), float64(po.height)
  35. wr := fow / fsw
  36. hr := foh / fsh
  37. var rate float64
  38. if po.resize == "fit" {
  39. rate = math.Min(wr, hr)
  40. } else {
  41. rate = math.Max(wr, hr)
  42. }
  43. return round(math.Min(fsw*rate, fow)), round(math.Min(fsh*rate, foh))
  44. }
  45. func processImage(p []byte, po processingOptions) ([]byte, error) {
  46. var err error
  47. img := bimg.NewImage(p)
  48. size, err := img.Size()
  49. if err != nil {
  50. return nil, err
  51. }
  52. // Default options
  53. opts := bimg.Options{
  54. Interpolator: bimg.Bicubic,
  55. Quality: conf.Quality,
  56. Gravity: po.gravity,
  57. Enlarge: po.enlarge,
  58. Type: po.format,
  59. }
  60. opts.Width, opts.Height = calcSize(size, po)
  61. switch po.resize {
  62. case "fit":
  63. opts.Embed = true
  64. case "fill":
  65. opts.Embed = true
  66. opts.Crop = true
  67. case "crop":
  68. opts.Crop = true
  69. default:
  70. opts.Force = true
  71. }
  72. return img.Process(opts)
  73. }