2014-05-15 14:44:19 +08:00
|
|
|
package images
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"image"
|
|
|
|
"image/gif"
|
|
|
|
"image/jpeg"
|
|
|
|
"image/png"
|
2014-10-27 02:34:55 +08:00
|
|
|
|
2016-06-03 09:09:14 +08:00
|
|
|
"github.com/chrislusf/seaweedfs/weed/glog"
|
2014-10-27 02:34:55 +08:00
|
|
|
"github.com/disintegration/imaging"
|
2014-05-15 14:44:19 +08:00
|
|
|
)
|
|
|
|
|
2014-07-05 15:43:41 +08:00
|
|
|
func Resized(ext string, data []byte, width, height int) (resized []byte, w int, h int) {
|
2014-05-15 14:44:19 +08:00
|
|
|
if width == 0 && height == 0 {
|
2014-07-05 15:43:41 +08:00
|
|
|
return data, 0, 0
|
2014-05-15 14:44:19 +08:00
|
|
|
}
|
2015-04-10 22:05:17 +08:00
|
|
|
srcImage, _, err := image.Decode(bytes.NewReader(data))
|
|
|
|
if err == nil {
|
2014-05-15 14:44:19 +08:00
|
|
|
bounds := srcImage.Bounds()
|
|
|
|
var dstImage *image.NRGBA
|
2014-07-05 15:43:41 +08: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)
|
|
|
|
}
|
2014-07-21 14:12:49 +08:00
|
|
|
} else {
|
|
|
|
return data, bounds.Dx(), bounds.Dy()
|
2014-05-15 14:44:19 +08:00
|
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
|
|
switch ext {
|
|
|
|
case ".png":
|
|
|
|
png.Encode(&buf, dstImage)
|
2014-07-05 09:03:48 +08:00
|
|
|
case ".jpg", ".jpeg":
|
2014-05-15 14:44:19 +08:00
|
|
|
jpeg.Encode(&buf, dstImage, nil)
|
|
|
|
case ".gif":
|
|
|
|
gif.Encode(&buf, dstImage, nil)
|
|
|
|
}
|
2014-07-05 15:43:41 +08:00
|
|
|
return buf.Bytes(), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
|
2015-04-10 22:05:17 +08:00
|
|
|
} else {
|
|
|
|
glog.Error(err)
|
2014-05-15 14:44:19 +08:00
|
|
|
}
|
2014-07-05 15:43:41 +08:00
|
|
|
return data, 0, 0
|
2014-05-15 14:44:19 +08:00
|
|
|
}
|