image_type.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package main
  2. /*
  3. #cgo LDFLAGS: -s -w
  4. #include "vips.h"
  5. */
  6. import "C"
  7. import (
  8. "fmt"
  9. "net/url"
  10. "path/filepath"
  11. "strings"
  12. )
  13. type imageType int
  14. const (
  15. imageTypeUnknown = imageType(C.UNKNOWN)
  16. imageTypeJPEG = imageType(C.JPEG)
  17. imageTypePNG = imageType(C.PNG)
  18. imageTypeWEBP = imageType(C.WEBP)
  19. imageTypeGIF = imageType(C.GIF)
  20. imageTypeICO = imageType(C.ICO)
  21. imageTypeSVG = imageType(C.SVG)
  22. imageTypeHEIC = imageType(C.HEIC)
  23. imageTypeTIFF = imageType(C.TIFF)
  24. contentDispositionFilenameFallback = "image"
  25. )
  26. var (
  27. imageTypes = map[string]imageType{
  28. "jpeg": imageTypeJPEG,
  29. "jpg": imageTypeJPEG,
  30. "png": imageTypePNG,
  31. "webp": imageTypeWEBP,
  32. "gif": imageTypeGIF,
  33. "ico": imageTypeICO,
  34. "svg": imageTypeSVG,
  35. "heic": imageTypeHEIC,
  36. "tiff": imageTypeTIFF,
  37. }
  38. mimes = map[imageType]string{
  39. imageTypeJPEG: "image/jpeg",
  40. imageTypePNG: "image/png",
  41. imageTypeWEBP: "image/webp",
  42. imageTypeGIF: "image/gif",
  43. imageTypeICO: "image/x-icon",
  44. imageTypeHEIC: "image/heif",
  45. imageTypeTIFF: "image/tiff",
  46. }
  47. contentDispositionsFmt = map[imageType]string{
  48. imageTypeJPEG: "inline; filename=\"%s.jpg\"",
  49. imageTypePNG: "inline; filename=\"%s.png\"",
  50. imageTypeWEBP: "inline; filename=\"%s.webp\"",
  51. imageTypeGIF: "inline; filename=\"%s.gif\"",
  52. imageTypeICO: "inline; filename=\"%s.ico\"",
  53. imageTypeHEIC: "inline; filename=\"%s.heic\"",
  54. imageTypeTIFF: "inline; filename=\"%s.tiff\"",
  55. }
  56. )
  57. func (it imageType) String() string {
  58. for k, v := range imageTypes {
  59. if v == it {
  60. return k
  61. }
  62. }
  63. return ""
  64. }
  65. func (it imageType) Mime() string {
  66. if mime, ok := mimes[it]; ok {
  67. return mime
  68. }
  69. return "application/octet-stream"
  70. }
  71. func (it imageType) ContentDisposition(filename string) string {
  72. format, ok := contentDispositionsFmt[it]
  73. if !ok {
  74. return "inline"
  75. }
  76. return fmt.Sprintf(format, filename)
  77. }
  78. func (it imageType) ContentDispositionFromURL(imageURL string) string {
  79. url, err := url.Parse(imageURL)
  80. if err != nil {
  81. return it.ContentDisposition(contentDispositionFilenameFallback)
  82. }
  83. _, filename := filepath.Split(url.Path)
  84. if len(filename) == 0 {
  85. return it.ContentDisposition(contentDispositionFilenameFallback)
  86. }
  87. return it.ContentDisposition(strings.TrimSuffix(filename, filepath.Ext(filename)))
  88. }