From defbc287f1218993e85bb149e3e746d16b2e6185 Mon Sep 17 00:00:00 2001 From: Andrew Gaul Date: Mon, 5 Jun 2017 14:11:50 +0200 Subject: [PATCH] Allow X-Compy-Quality override header This allows clients to override the configured compression quality. Fixes #14. --- compy_test.go | 28 ++++++++++++++++++++++++++++ transcoder/jpeg.go | 15 +++++++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/compy_test.go b/compy_test.go index 2179286..f071fc4 100644 --- a/compy_test.go +++ b/compy_test.go @@ -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) diff --git a/transcoder/jpeg.go b/transcoder/jpeg.go index 4c5e371..c6368cf 100644 --- a/transcoder/jpeg.go +++ b/transcoder/jpeg.go @@ -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 } }