mirror of
https://github.com/willnorris/imageproxy.git
synced 2024-12-30 22:34:18 -05:00
add support for image resizing
This commit is contained in:
parent
f6f757a75d
commit
45d07f2378
2 changed files with 51 additions and 0 deletions
|
@ -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)
|
||||
|
|
48
transform/transform.go
Normal file
48
transform/transform.go
Normal file
|
@ -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
|
||||
}
|
Loading…
Reference in a new issue