Merge pull request #10 from andrewgaul/webp

Add PNG and JPEG to WebP transcoding
This commit is contained in:
Barna Csorogi 2017-01-16 22:43:40 +01:00 committed by GitHub
commit cde47b46f3
4 changed files with 43 additions and 5 deletions

View file

@ -14,7 +14,7 @@ Features:
- gzip compression - gzip compression
- transcode animated gifs to static images - transcode animated gifs to static images
- transcode jpeg images to desired quality using libjpeg - transcode jpeg images to desired quality using libjpeg
- transcode png images - transcode PNG and JPEG images to WebP
- html/css/js minification - html/css/js minification

View file

@ -2,6 +2,7 @@ package transcoder
import ( import (
"github.com/barnacs/compy/proxy" "github.com/barnacs/compy/proxy"
"github.com/chai2010/webp"
"github.com/pixiv/go-libjpeg/jpeg" "github.com/pixiv/go-libjpeg/jpeg"
"net/http" "net/http"
) )
@ -26,8 +27,19 @@ func (t *Jpeg) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, heade
if err != nil { if err != nil {
return err return err
} }
if err = jpeg.Encode(w, img, t.encOptions); err != nil {
return err if SupportsWebP(headers) {
options := webp.Options{
Lossless: false,
Quality: float32(t.encOptions.Quality),
}
if err = webp.Encode(w, img, &options); err != nil {
return err
}
} else {
if err = jpeg.Encode(w, img, t.encOptions); err != nil {
return err
}
} }
return nil return nil
} }

View file

@ -2,6 +2,7 @@ package transcoder
import ( import (
"github.com/barnacs/compy/proxy" "github.com/barnacs/compy/proxy"
"github.com/chai2010/webp"
"image/png" "image/png"
"net/http" "net/http"
) )
@ -13,8 +14,18 @@ func (t *Png) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, header
if err != nil { if err != nil {
return err return err
} }
if err = png.Encode(w, img); err != nil {
return err if SupportsWebP(headers) {
options := webp.Options{
Lossless: true,
}
if err = webp.Encode(w, img, &options); err != nil {
return err
}
} else {
if err = png.Encode(w, img); err != nil {
return err
}
} }
return nil return nil
} }

15
transcoder/util.go Normal file
View file

@ -0,0 +1,15 @@
package transcoder
import (
"net/http"
"strings"
)
func SupportsWebP(headers http.Header) bool {
for _, v := range strings.Split(headers.Get("Accept"), ",") {
if strings.SplitN(v, ";", 2)[0] == "image/webp" {
return true
}
}
return false
}