image_type.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. contentDispositionFilenameFallback = "image"
  24. )
  25. var (
  26. imageTypes = map[string]imageType{
  27. "jpeg": imageTypeJPEG,
  28. "jpg": imageTypeJPEG,
  29. "png": imageTypePNG,
  30. "webp": imageTypeWEBP,
  31. "gif": imageTypeGIF,
  32. "ico": imageTypeICO,
  33. "svg": imageTypeSVG,
  34. "heic": imageTypeHEIC,
  35. }
  36. mimes = map[imageType]string{
  37. imageTypeJPEG: "image/jpeg",
  38. imageTypePNG: "image/png",
  39. imageTypeWEBP: "image/webp",
  40. imageTypeGIF: "image/gif",
  41. imageTypeICO: "image/x-icon",
  42. imageTypeHEIC: "image/heif",
  43. }
  44. contentDispositionsFmt = map[imageType]string{
  45. imageTypeJPEG: "inline; filename=\"%s.jpg\"",
  46. imageTypePNG: "inline; filename=\"%s.png\"",
  47. imageTypeWEBP: "inline; filename=\"%s.webp\"",
  48. imageTypeGIF: "inline; filename=\"%s.gif\"",
  49. imageTypeICO: "inline; filename=\"%s.ico\"",
  50. imageTypeHEIC: "inline; filename=\"%s.heic\"",
  51. }
  52. )
  53. func (it imageType) String() string {
  54. for k, v := range imageTypes {
  55. if v == it {
  56. return k
  57. }
  58. }
  59. return ""
  60. }
  61. func (it imageType) Mime() string {
  62. if mime, ok := mimes[it]; ok {
  63. return mime
  64. }
  65. return "application/octet-stream"
  66. }
  67. func (it imageType) ContentDisposition(filename string) string {
  68. format, ok := contentDispositionsFmt[it]
  69. if !ok {
  70. return "inline"
  71. }
  72. return fmt.Sprintf(format, filename)
  73. }
  74. func (it imageType) ContentDispositionFromURL(imageURL string) string {
  75. url, err := url.Parse(imageURL)
  76. if err != nil {
  77. return it.ContentDisposition(contentDispositionFilenameFallback)
  78. }
  79. _, filename := filepath.Split(url.Path)
  80. if len(filename) == 0 {
  81. return it.ContentDisposition(contentDispositionFilenameFallback)
  82. }
  83. return it.ContentDisposition(strings.TrimSuffix(filename, filepath.Ext(filename)))
  84. }