/
read_write.go
143 lines (129 loc) · 2.42 KB
/
read_write.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package image
import (
"bytes"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"log"
"github.com/chai2010/webp"
"github.com/liut/jpegquality"
)
// consts
const (
MinJPEGQuality = jpeg.DefaultQuality // 75
MinWebpQuality = 80
)
const (
formatGIF = "gif"
formatJPEG = "jpeg"
formatPNG = "png"
formatWEBP = "webp"
)
var (
mtypes = map[string]string{
formatGIF: "image/gif",
formatJPEG: "image/jpeg",
formatPNG: "image/png",
formatWEBP: "image/webp",
}
)
// Image ...
type Image struct {
m image.Image
*Attr
Format string
rs io.ReadSeeker
rn int // read length
}
// Open ...
func Open(rs io.ReadSeeker) (*Image, error) {
cw := new(CountWriter)
m, format, err := image.Decode(io.TeeReader(rs, cw))
if err != nil {
return nil, err
}
pt := m.Bounds().Max
attr := NewAttr(uint(pt.X), uint(pt.Y), format)
if mt, ok := mtypes[format]; ok {
attr.Mime = mt
}
attr.Size = Size(cw.Len())
if format == formatJPEG {
jr, err := jpegquality.New(rs)
if err != nil {
return nil, err
}
attr.Quality = Quality(jr.Quality())
}
return &Image{
m: m,
Attr: attr,
Format: format,
rs: rs,
rn: cw.Len(),
}, nil
}
// WriteOption ...
type WriteOption struct {
Format string
StripAll bool
Quality Quality
}
// SaveTo ...
func (im *Image) SaveTo(w io.Writer, opt WriteOption) error {
if opt.Format == "" {
opt.Format = im.Format
}
var buf bytes.Buffer
n, err := SaveTo(&buf, im.m, opt)
if err != nil {
return err
}
var nn int64
if n > im.rn {
log.Printf("saved %d, im size %d", n, im.rn)
im.rs.Seek(0, 0)
nn, err = io.Copy(w, im.rs)
} else {
nn, err = io.Copy(w, &buf)
}
log.Printf("copied %d bytes", nn)
return err
}
// SaveTo ...
func SaveTo(w io.Writer, m image.Image, opt WriteOption) (n int, err error) {
cw := new(CountWriter)
defer func() { n = cw.Len() }()
w = io.MultiWriter(w, cw)
switch opt.Format {
case formatJPEG:
qlt := int(opt.Quality)
if qlt == 0 {
qlt = MinJPEGQuality
}
err = jpeg.Encode(w, m, &jpeg.Options{Quality: qlt})
return
case formatGIF:
err = gif.Encode(w, m, &gif.Options{
NumColors: 256,
Quantizer: nil,
Drawer: nil,
})
return
case formatPNG:
err = png.Encode(w, m)
return
case formatWEBP:
qlt := int(opt.Quality)
if qlt == 0 {
qlt = MinWebpQuality
}
err = webp.Encode(w, m, &webp.Options{Quality: float32(qlt)})
return
}
log.Printf("opt %v", opt)
err = ErrorFormat
return
}