From 45d07f2378b94598f59fcbad3af1aeff03f14aa3 Mon Sep 17 00:00:00 2001 From: Will Norris Date: Wed, 4 Dec 2013 23:42:59 -0800 Subject: [PATCH] add support for image resizing --- proxy/proxy.go | 3 +++ transform/transform.go | 48 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 transform/transform.go diff --git a/proxy/proxy.go b/proxy/proxy.go index c5485ab..08788dc 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -14,6 +14,7 @@ import ( "github.com/golang/glog" "github.com/willnorris/go-imageproxy/cache" "github.com/willnorris/go-imageproxy/data" + "github.com/willnorris/go-imageproxy/transform" ) // URLError reports a malformed URL error. @@ -115,6 +116,8 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { glog.Infof("serving from cache") } + image, _ = transform.Transform(*image, req.Options) + w.Header().Add("Content-Length", strconv.Itoa(len(image.Bytes))) w.Header().Add("Expires", image.Expires.Format(time.RFC1123)) w.Write(image.Bytes) diff --git a/transform/transform.go b/transform/transform.go new file mode 100644 index 0000000..53f6903 --- /dev/null +++ b/transform/transform.go @@ -0,0 +1,48 @@ +// Package transform handles image transformation such as resizing. +package transform + +import ( + "bytes" + "image" + "image/gif" + "image/jpeg" + "image/png" + + "github.com/nfnt/resize" + "github.com/willnorris/go-imageproxy/data" +) + +// Transform the provided image. +func Transform(img data.Image, opt *data.Options) (*data.Image, error) { + if opt == nil { + return &img, nil + } + + // decode image + m, format, err := image.Decode(bytes.NewReader(img.Bytes)) + if err != nil { + return nil, err + } + + // resize + if opt.Width != 0 || opt.Height != 0 { + m = resize.Resize(uint(opt.Width), uint(opt.Height), m, resize.Lanczos3) + } + + // encode image + buf := new(bytes.Buffer) + switch format { + case "gif": + gif.Encode(buf, m, nil) + break + case "jpeg": + jpeg.Encode(buf, m, nil) + break + case "png": + png.Encode(buf, m) + break + } + + img.Bytes = buf.Bytes() + return &img, nil +}