From e5056553385dc84354b6640d5132642319b295e2 Mon Sep 17 00:00:00 2001 From: Andrew Gaul Date: Thu, 19 Jan 2017 11:38:48 -0800 Subject: [PATCH] Add GIF to WebP transcoding --- compy_test.go | 15 +++++++++++++++ transcoder/gif.go | 15 +++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/compy_test.go b/compy_test.go index 887d890..8a25180 100644 --- a/compy_test.go +++ b/compy_test.go @@ -134,6 +134,21 @@ func (s *CompyTest) TestGif(c *C) { c.Assert(uncompressedLength > compressedLength, Equals, true) } +func (s *CompyTest) TestGifToWebP(c *C) { + req, err := http.NewRequest("GET", s.server.URL+"/image/gif", nil) + c.Assert(err, IsNil) + req.Header.Add("Accept", "image/webp") + + 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/webp") + + _, err = webp.Decode(resp.Body) + c.Assert(err, IsNil) +} + func (s *CompyTest) TestJpeg(c *C) { resp, err := s.client.Get(s.server.URL + "/image/jpeg") c.Assert(err, IsNil) diff --git a/transcoder/gif.go b/transcoder/gif.go index eb0392d..a4901b6 100644 --- a/transcoder/gif.go +++ b/transcoder/gif.go @@ -2,6 +2,7 @@ package transcoder import ( "github.com/barnacs/compy/proxy" + "github.com/chai2010/webp" "image/gif" "net/http" ) @@ -13,8 +14,18 @@ func (t *Gif) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, header if err != nil { return err } - if err = gif.Encode(w, img, nil); err != nil { - return err + if SupportsWebP(headers) { + w.Header().Set("Content-Type", "image/webp") + options := webp.Options{ + Lossless: true, + } + if err = webp.Encode(w, img, &options); err != nil { + return err + } + } else { + if err = gif.Encode(w, img, nil); err != nil { + return err + } } return nil }