forked from barnacs/compy
/
jpeg.go
57 lines (51 loc) · 1.15 KB
/
jpeg.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
package transcoder
import (
"github.com/barnacs/compy/proxy"
"github.com/chai2010/webp"
"github.com/pixiv/go-libjpeg/jpeg"
"net/http"
"strconv"
)
type Jpeg struct {
decOptions *jpeg.DecoderOptions
encOptions *jpeg.EncoderOptions
}
func NewJpeg(quality int) *Jpeg {
return &Jpeg{
decOptions: &jpeg.DecoderOptions{},
encOptions: &jpeg.EncoderOptions{
Quality: quality,
OptimizeCoding: true,
},
}
}
func (t *Jpeg) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, headers http.Header) error {
img, err := jpeg.Decode(r, t.decOptions)
if err != nil {
return err
}
encOptions := t.encOptions
qualityString := headers.Get("X-Compy-Quality")
if qualityString != "" {
if quality, err := strconv.Atoi(qualityString); err != nil {
return err
} else {
encOptions.Quality = quality
}
}
if SupportsWebP(headers) {
w.Header().Set("Content-Type", "image/webp")
options := webp.Options{
Lossless: false,
Quality: float32(encOptions.Quality),
}
if err = webp.Encode(w, img, &options); err != nil {
return err
}
} else {
if err = jpeg.Encode(w, img, encOptions); err != nil {
return err
}
}
return nil
}