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. }
  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. Compression: conf.Compression,
  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. }