utils.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package media
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "regexp"
  6. "strings"
  7. "github.com/disintegration/imaging"
  8. "github.com/qor5/admin/utils"
  9. )
  10. func GetImageFormat(url string) (*imaging.Format, error) {
  11. formats := map[string]imaging.Format{
  12. ".jpg": imaging.JPEG,
  13. ".jpeg": imaging.JPEG,
  14. ".png": imaging.PNG,
  15. ".tif": imaging.TIFF,
  16. ".tiff": imaging.TIFF,
  17. ".bmp": imaging.BMP,
  18. ".gif": imaging.GIF,
  19. }
  20. ext := strings.ToLower(regexp.MustCompile(`(\?.*?$)`).ReplaceAllString(filepath.Ext(url), ""))
  21. if f, ok := formats[ext]; ok {
  22. return &f, nil
  23. }
  24. return nil, imaging.ErrUnsupportedFormat
  25. }
  26. // IsImageFormat check filename is image or not
  27. func IsImageFormat(name string) bool {
  28. _, err := GetImageFormat(name)
  29. return err == nil
  30. }
  31. // IsVideoFormat check filename is video or not
  32. func IsVideoFormat(name string) bool {
  33. formats := []string{".mp4", ".m4p", ".m4v", ".m4v", ".mov", ".mpeg", ".webm", ".avi", ".ogg", ".ogv"}
  34. ext := strings.ToLower(regexp.MustCompile(`(\?.*?$)`).ReplaceAllString(filepath.Ext(name), ""))
  35. for _, format := range formats {
  36. if format == ext {
  37. return true
  38. }
  39. }
  40. return false
  41. }
  42. func IsSVGFormat(name string) bool {
  43. formats := []string{".svg", ".svgz"}
  44. ext := strings.ToLower(regexp.MustCompile(`(\?.*?$)`).ReplaceAllString(filepath.Ext(name), ""))
  45. for _, format := range formats {
  46. if format == ext {
  47. return true
  48. }
  49. }
  50. return false
  51. }
  52. func parseTagOption(str string) *Option {
  53. option := Option(utils.ParseTagOption(str))
  54. return &option
  55. }
  56. func ByteCountSI(b int) string {
  57. const unit = 1000
  58. if b < unit {
  59. return fmt.Sprintf("%dB", b)
  60. }
  61. div, exp := unit, 0
  62. for n := b / unit; n >= unit; n /= unit {
  63. div *= unit
  64. exp++
  65. }
  66. format := "%.1f%cB"
  67. suffix := "kMGTPE"[exp]
  68. if suffix == 'k' {
  69. format = "%.f%cB"
  70. }
  71. return fmt.Sprintf(format,
  72. float64(b)/float64(div), suffix)
  73. }