Allow X-Compy-Quality override header

This allows clients to override the configured compression quality.
Fixes #14.
This commit is contained in:
Andrew Gaul 2017-06-05 14:11:50 +02:00
parent 69b89413bd
commit defbc287f1
2 changed files with 41 additions and 2 deletions

View file

@ -145,6 +145,34 @@ func (s *CompyTest) TestJpeg(c *C) {
c.Assert(err, IsNil)
}
func (s *CompyTest) TestJpegQuality(c *C) {
req, err := http.NewRequest("GET", s.server.URL+"/image/jpeg", nil)
c.Assert(err, IsNil)
req.Header.Add("X-Compy-Quality", "10")
resp, err := s.client.Do(req)
c.Assert(err, IsNil)
defer resp.Body.Close()
c.Assert(resp.StatusCode, Equals, 200)
c.Assert(resp.Header.Get("Content-Type"), Equals, "image/jpeg")
len10, err := new(bytes.Buffer).ReadFrom(resp.Body)
c.Assert(err, IsNil)
req, err = http.NewRequest("GET", s.server.URL+"/image/jpeg", nil)
c.Assert(err, IsNil)
req.Header.Add("X-Compy-Quality", "90")
resp, err = s.client.Do(req)
c.Assert(err, IsNil)
defer resp.Body.Close()
c.Assert(resp.StatusCode, Equals, 200)
c.Assert(resp.Header.Get("Content-Type"), Equals, "image/jpeg")
len90, err := new(bytes.Buffer).ReadFrom(resp.Body)
c.Assert(err, IsNil)
c.Assert(len10 < len90, Equals, true)
}
func (s *CompyTest) TestJpegToWebP(c *C) {
req, err := http.NewRequest("GET", s.server.URL+"/image/jpeg", nil)
c.Assert(err, IsNil)

View file

@ -5,6 +5,7 @@ import (
"github.com/chai2010/webp"
"github.com/pixiv/go-libjpeg/jpeg"
"net/http"
"strconv"
)
type Jpeg struct {
@ -28,17 +29,27 @@ func (t *Jpeg) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, heade
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(t.encOptions.Quality),
Quality: float32(encOptions.Quality),
}
if err = webp.Encode(w, img, &options); err != nil {
return err
}
} else {
if err = jpeg.Encode(w, img, t.encOptions); err != nil {
if err = jpeg.Encode(w, img, encOptions); err != nil {
return err
}
}