2014-05-15 06:44:19 +00:00
|
|
|
package images
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"github.com/disintegration/imaging"
|
|
|
|
"image"
|
|
|
|
"image/gif"
|
|
|
|
"image/jpeg"
|
|
|
|
"image/png"
|
|
|
|
)
|
|
|
|
|
2014-07-05 07:43:41 +00:00
|
|
|
func Resized(ext string, data []byte, width, height int) (resized []byte, w int, h int) {
|
2014-05-15 06:44:19 +00:00
|
|
|
if width == 0 && height == 0 {
|
2014-07-05 07:43:41 +00:00
|
|
|
return data, 0, 0
|
2014-05-15 06:44:19 +00:00
|
|
|
}
|
|
|
|
if srcImage, _, err := image.Decode(bytes.NewReader(data)); err == nil {
|
|
|
|
bounds := srcImage.Bounds()
|
|
|
|
var dstImage *image.NRGBA
|
2014-07-05 07:43:41 +00:00
|
|
|
if bounds.Dx() > width && width != 0 || bounds.Dy() > height && height != 0 {
|
|
|
|
if width == height && bounds.Dx() != bounds.Dy() {
|
|
|
|
dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
|
|
|
|
w, h = width, height
|
|
|
|
} else {
|
|
|
|
dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
|
|
|
|
}
|
|
|
|
}else{
|
|
|
|
return data, bounds.Dx(), bounds.Dy()
|
2014-05-15 06:44:19 +00:00
|
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
|
|
switch ext {
|
|
|
|
case ".png":
|
|
|
|
png.Encode(&buf, dstImage)
|
2014-07-05 01:03:48 +00:00
|
|
|
case ".jpg", ".jpeg":
|
2014-05-15 06:44:19 +00:00
|
|
|
jpeg.Encode(&buf, dstImage, nil)
|
|
|
|
case ".gif":
|
|
|
|
gif.Encode(&buf, dstImage, nil)
|
|
|
|
}
|
2014-07-05 07:43:41 +00:00
|
|
|
return buf.Bytes(), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
|
2014-05-15 06:44:19 +00:00
|
|
|
}
|
2014-07-05 07:43:41 +00:00
|
|
|
return data, 0, 0
|
2014-05-15 06:44:19 +00:00
|
|
|
}
|