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