2014-05-15 06:44:19 +00:00
|
|
|
package images
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"image"
|
|
|
|
"image/gif"
|
|
|
|
"image/jpeg"
|
|
|
|
"image/png"
|
2014-10-26 18:34:55 +00:00
|
|
|
|
2016-06-03 01:09:14 +00:00
|
|
|
"github.com/chrislusf/seaweedfs/weed/glog"
|
2014-10-26 18:34:55 +00:00
|
|
|
"github.com/disintegration/imaging"
|
2014-05-15 06:44:19 +00:00
|
|
|
)
|
|
|
|
|
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
|
|
|
}
|
2015-04-10 14:05:17 +00:00
|
|
|
srcImage, _, err := image.Decode(bytes.NewReader(data))
|
|
|
|
if err == nil {
|
2014-05-15 06:44:19 +00:00
|
|
|
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)
|
|
|
|
}
|
2014-07-21 06:12:49 +00:00
|
|
|
} 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()
|
2015-04-10 14:05:17 +00:00
|
|
|
} else {
|
|
|
|
glog.Error(err)
|
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
|
|
|
}
|