handlers.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package media
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "image"
  6. "image/color"
  7. "image/draw"
  8. "image/gif"
  9. _ "image/jpeg"
  10. "io/ioutil"
  11. "math"
  12. "github.com/disintegration/imaging"
  13. )
  14. var mediaHandlers = make(map[string]MediaHandler)
  15. var DefaultSizeKey = "default"
  16. // MediaHandler media library handler interface, defined which files could be handled, and the handler
  17. type MediaHandler interface {
  18. CouldHandle(media Media) bool
  19. Handle(media Media, file FileInterface, option *Option) error
  20. }
  21. // RegisterMediaHandler register Media library handler
  22. func RegisterMediaHandler(name string, handler MediaHandler) {
  23. mediaHandlers[name] = handler
  24. }
  25. // imageHandler default image handler
  26. type imageHandler struct{}
  27. func (imageHandler) CouldHandle(media Media) bool {
  28. return media.IsImage()
  29. }
  30. func resizeImageTo(img image.Image, size *Size, format imaging.Format) image.Image {
  31. imgSize := img.Bounds().Size()
  32. switch {
  33. case size.Padding:
  34. var (
  35. backgroundColor = image.NewUniform(color.Transparent)
  36. ratioX = float64(size.Width) / float64(imgSize.X)
  37. ratioY = float64(size.Height) / float64(imgSize.Y)
  38. // 100x200 -> 200x300 ==> ratioX = 2, ratioY = 1.5 ==> resize to (x1.5) = 150x300
  39. // 100x200 -> 20x50 ==> ratioX = 0.2, ratioY = 0.4 ==> resize to (x0.2) = 20x40
  40. // 100x200 -> 50x0 ==> ratioX = 0.5, ratioY = 0 ==> resize to (x0.5) = 50x100
  41. minRatio = math.Min(ratioX, ratioY)
  42. )
  43. if format == imaging.JPEG {
  44. backgroundColor = image.NewUniform(color.White)
  45. }
  46. background := imaging.New(size.Width, size.Height, backgroundColor)
  47. fixFloat := func(x float64, y int) int {
  48. if math.Abs(x-float64(y)) < 1 {
  49. return y
  50. }
  51. return int(x)
  52. }
  53. if minRatio == 0 {
  54. minRatio = math.Max(ratioX, ratioY)
  55. if size.Width == 0 && size.Height != 0 {
  56. // size 50x0, source 100x200 => crop to 50x100
  57. newWidth := int(float64(imgSize.X) / float64(imgSize.Y) * float64(size.Height))
  58. background = imaging.New(newWidth, size.Height, backgroundColor)
  59. } else if size.Height == 0 && size.Width != 0 {
  60. // size 0x50, source 100x200 => crop to 25x50
  61. newHeight := int(float64(imgSize.Y) / float64(imgSize.X) * float64(size.Width))
  62. background = imaging.New(size.Width, newHeight, backgroundColor)
  63. } else if size.Height == 0 && size.Width == 0 {
  64. minRatio = 1
  65. background = imaging.New(imgSize.X, imgSize.Y, backgroundColor)
  66. }
  67. }
  68. backgroundSize := background.Bounds().Size()
  69. img = imaging.Resize(img, fixFloat(float64(imgSize.X)*minRatio, backgroundSize.X), fixFloat(float64(imgSize.Y)*minRatio, backgroundSize.Y), imaging.CatmullRom)
  70. return imaging.PasteCenter(background, img)
  71. default:
  72. width, height := size.Width, size.Height
  73. if width == 0 && height != 0 {
  74. // size 50x0, source 100x200 => crop to 50x100
  75. width = int(float64(imgSize.X) / float64(imgSize.Y) * float64(size.Height))
  76. } else if height == 0 && width != 0 {
  77. // size 0x50, source 100x200 => crop to 25x50
  78. height = int(float64(imgSize.Y) / float64(imgSize.X) * float64(size.Width))
  79. } else if height == 0 && width == 0 {
  80. width, height = imgSize.X, imgSize.Y
  81. }
  82. return imaging.Thumbnail(img, width, height, imaging.Lanczos)
  83. }
  84. }
  85. func (imageHandler) Handle(media Media, file FileInterface, option *Option) (err error) {
  86. fileBytes, err := ioutil.ReadAll(file)
  87. if err != nil {
  88. return
  89. }
  90. fileSizes := media.GetFileSizes()
  91. originalFileSize := len(fileBytes)
  92. fileSizes["original"] = originalFileSize
  93. file.Seek(0, 0)
  94. err = media.Store(media.URL("original"), option, file)
  95. if err != nil {
  96. return
  97. }
  98. file.Seek(0, 0)
  99. format, err := GetImageFormat(media.URL())
  100. if err != nil {
  101. return
  102. }
  103. if *format == imaging.GIF {
  104. err = handleGIF(media, file, option, fileSizes, format)
  105. if err != nil {
  106. return
  107. }
  108. SetFileSizes(media, fileSizes)
  109. return
  110. }
  111. img, _, err := image.Decode(file)
  112. if err != nil {
  113. return
  114. }
  115. SetWeightHeight(media, img.Bounds().Dx(), img.Bounds().Dy())
  116. // Save cropped default image
  117. if cropOption := media.GetCropOption(DefaultSizeKey); cropOption != nil {
  118. var buffer bytes.Buffer
  119. imaging.Encode(&buffer, imaging.Crop(img, *cropOption), *format)
  120. fileSizes[DefaultSizeKey] = buffer.Len()
  121. media.Store(media.URL(), option, &buffer)
  122. } else {
  123. file.Seek(0, 0)
  124. // Save default image
  125. fileSizes[DefaultSizeKey] = originalFileSize
  126. media.Store(media.URL(), option, file)
  127. }
  128. // save sizes image
  129. for key, size := range media.GetSizes() {
  130. if key == DefaultSizeKey {
  131. continue
  132. }
  133. newImage := img
  134. if cropOption := media.GetCropOption(key); cropOption != nil {
  135. newImage = imaging.Crop(newImage, *cropOption)
  136. }
  137. var buffer bytes.Buffer
  138. imaging.Encode(&buffer, resizeImageTo(newImage, size, *format), *format)
  139. fileSizes[key] = buffer.Len()
  140. media.Store(media.URL(key), option, &buffer)
  141. }
  142. SetFileSizes(media, fileSizes)
  143. return
  144. }
  145. func handleGIF(media Media, file FileInterface, option *Option, fileSizes map[string]int, format *imaging.Format) error {
  146. var buffer bytes.Buffer
  147. g, err := gif.DecodeAll(file)
  148. if err != nil {
  149. return err
  150. }
  151. SetWeightHeight(media, g.Config.Width, g.Config.Height)
  152. if cropOption := media.GetCropOption(DefaultSizeKey); cropOption != nil {
  153. for i := range g.Image {
  154. img := imaging.Crop(g.Image[i], *cropOption)
  155. g.Image[i] = image.NewPaletted(img.Rect, g.Image[i].Palette)
  156. draw.Draw(g.Image[i], img.Rect, img, image.Pt(0, 0), draw.Src)
  157. if i == 0 {
  158. g.Config.Width = img.Rect.Dx()
  159. g.Config.Height = img.Rect.Dy()
  160. }
  161. }
  162. }
  163. gif.EncodeAll(&buffer, g)
  164. fileSizes[DefaultSizeKey] = buffer.Len()
  165. media.Store(media.URL(), option, &buffer)
  166. // save sizes image
  167. for key, size := range media.GetSizes() {
  168. if key == DefaultSizeKey {
  169. continue
  170. }
  171. file.Seek(0, 0)
  172. g, err := gif.DecodeAll(file)
  173. if err != nil {
  174. return err
  175. }
  176. for i := range g.Image {
  177. var img image.Image = g.Image[i]
  178. if cropOption := media.GetCropOption(key); cropOption != nil {
  179. img = imaging.Crop(g.Image[i], *cropOption)
  180. }
  181. img = resizeImageTo(img, size, *format)
  182. g.Image[i] = image.NewPaletted(image.Rect(0, 0, size.Width, size.Height), g.Image[i].Palette)
  183. draw.Draw(g.Image[i], image.Rect(0, 0, size.Width, size.Height), img, image.Pt(0, 0), draw.Src)
  184. }
  185. var buffer bytes.Buffer
  186. g.Config.Width = size.Width
  187. g.Config.Height = size.Height
  188. gif.EncodeAll(&buffer, g)
  189. fileSizes[key] = buffer.Len()
  190. media.Store(media.URL(key), option, &buffer)
  191. }
  192. return nil
  193. }
  194. func SetWeightHeight(media Media, width, height int) {
  195. result, _ := json.Marshal(map[string]int{"Width": width, "Height": height})
  196. media.Scan(string(result))
  197. }
  198. func SetFileSizes(media Media, fileSizes map[string]int) {
  199. result, _ := json.Marshal(map[string]map[string]int{"FileSizes": fileSizes})
  200. media.Scan(string(result))
  201. }
  202. func init() {
  203. RegisterMediaHandler("image_handler", imageHandler{})
  204. }