-
Notifications
You must be signed in to change notification settings - Fork 244
/
decode.go
121 lines (105 loc) · 2.08 KB
/
decode.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
111
112
113
114
115
116
117
118
119
120
121
package images
import (
"errors"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"os"
"golang.org/x/image/webp"
)
func Decode(fileName string) (image.Image, error) {
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer file.Close()
fb, err := prepareFileForDecode(file)
if err != nil {
return nil, err
}
return decodeImageData(fb, file)
}
func prepareFileForDecode(file *os.File) ([]byte, error) {
// Read the first 14 bytes, used for performing image type checks before parsing the image data
fb := make([]byte, 14)
_, err := file.Read(fb)
if err != nil {
return nil, err
}
// Reset the read cursor
_, err = file.Seek(0, 0)
if err != nil {
return nil, err
}
return fb, nil
}
func decodeImageData(buf []byte, r io.Reader) (img image.Image, err error) {
switch GetType(buf) {
case JPEG:
img, err = jpeg.Decode(r)
case PNG:
img, err = png.Decode(r)
case GIF:
img, err = gif.Decode(r)
case WEBP:
img, err = webp.Decode(r)
case UNKNOWN:
fallthrough
default:
return nil, errors.New("unsupported file type")
}
if err != nil {
return nil, err
}
return img, nil
}
func GetType(buf []byte) ImageType {
switch {
case isJpeg(buf):
return JPEG
case isPng(buf):
return PNG
case isGif(buf):
return GIF
case isWebp(buf):
return WEBP
default:
return UNKNOWN
}
}
func GetMimeType(buf []byte) (string, error) {
switch {
case isJpeg(buf):
return "jpeg", nil
case isPng(buf):
return "png", nil
case isGif(buf):
return "gif", nil
case isWebp(buf):
return "webp", nil
default:
return "", errors.New("image format not supported")
}
}
func isJpeg(buf []byte) bool {
return len(buf) > 2 &&
buf[0] == 0xFF &&
buf[1] == 0xD8 &&
buf[2] == 0xFF
}
func isPng(buf []byte) bool {
return len(buf) > 3 &&
buf[0] == 0x89 && buf[1] == 0x50 &&
buf[2] == 0x4E && buf[3] == 0x47
}
func isGif(buf []byte) bool {
return len(buf) > 2 &&
buf[0] == 0x47 && buf[1] == 0x49 && buf[2] == 0x46
}
func isWebp(buf []byte) bool {
return len(buf) > 11 &&
buf[8] == 0x57 && buf[9] == 0x45 &&
buf[10] == 0x42 && buf[11] == 0x50
}