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
|
|
|
|
2019-09-12 13:18:21 +00:00
|
|
|
"github.com/chrislusf/seaweedfs/weed/glog"
|
2014-10-26 18:34:55 +00:00
|
|
|
"github.com/disintegration/imaging"
|
2018-07-05 02:34:17 +00:00
|
|
|
"io"
|
2014-05-15 06:44:19 +00:00
|
|
|
)
|
|
|
|
|
2018-07-05 02:34:17 +00:00
|
|
|
func Resized(ext string, read io.ReadSeeker, width, height int, mode string) (resized io.ReadSeeker, w int, h int) {
|
2014-05-15 06:44:19 +00:00
|
|
|
if width == 0 && height == 0 {
|
2018-07-05 02:34:17 +00:00
|
|
|
return read, 0, 0
|
2014-05-15 06:44:19 +00:00
|
|
|
}
|
2018-07-05 02:34:17 +00:00
|
|
|
srcImage, _, err := image.Decode(read)
|
2015-04-10 14:05:17 +00:00
|
|
|
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 {
|
2017-05-05 09:17:30 +00:00
|
|
|
switch mode {
|
|
|
|
case "fit":
|
|
|
|
dstImage = imaging.Fit(srcImage, width, height, imaging.Lanczos)
|
|
|
|
case "fill":
|
|
|
|
dstImage = imaging.Fill(srcImage, width, height, imaging.Center, imaging.Lanczos)
|
|
|
|
default:
|
|
|
|
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-05 07:43:41 +00:00
|
|
|
}
|
2014-07-21 06:12:49 +00:00
|
|
|
} else {
|
2018-07-05 02:34:17 +00:00
|
|
|
return read, 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)
|
|
|
|
}
|
2018-07-05 02:34:17 +00:00
|
|
|
return bytes.NewReader(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
|
|
|
}
|
2018-07-05 02:34:17 +00:00
|
|
|
return read, 0, 0
|
2014-05-15 06:44:19 +00:00
|
|
|
}
|