2014-05-15 14:44:19 +08:00
|
|
|
package images
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"image"
|
|
|
|
"image/gif"
|
|
|
|
"image/jpeg"
|
|
|
|
"image/png"
|
2020-03-22 13:16:00 +08:00
|
|
|
"io"
|
2014-10-27 02:34:55 +08:00
|
|
|
|
|
|
|
"github.com/disintegration/imaging"
|
2020-03-22 13:16:00 +08:00
|
|
|
|
2022-07-29 15:17:28 +08:00
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
2021-07-24 13:26:40 +08:00
|
|
|
|
|
|
|
_ "golang.org/x/image/webp"
|
2014-05-15 14:44:19 +08:00
|
|
|
)
|
|
|
|
|
2018-07-05 10:34:17 +08:00
|
|
|
func Resized(ext string, read io.ReadSeeker, width, height int, mode string) (resized io.ReadSeeker, w int, h int) {
|
2014-05-15 14:44:19 +08:00
|
|
|
if width == 0 && height == 0 {
|
2018-07-05 10:34:17 +08:00
|
|
|
return read, 0, 0
|
2014-05-15 14:44:19 +08:00
|
|
|
}
|
2018-07-05 10:34:17 +08:00
|
|
|
srcImage, _, err := image.Decode(read)
|
2015-04-10 22:05:17 +08:00
|
|
|
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 {
|
2017-05-05 17:17:30 +08: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 15:43:41 +08:00
|
|
|
}
|
2014-07-21 14:12:49 +08:00
|
|
|
} else {
|
2020-03-22 13:16:00 +08:00
|
|
|
read.Seek(0, 0)
|
2018-07-05 10:34:17 +08:00
|
|
|
return read, 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)
|
2021-07-24 13:26:40 +08:00
|
|
|
case ".webp":
|
|
|
|
// Webp does not have golang encoder.
|
|
|
|
png.Encode(&buf, dstImage)
|
2014-05-15 14:44:19 +08:00
|
|
|
}
|
2018-07-05 10:34:17 +08:00
|
|
|
return bytes.NewReader(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
|
|
|
}
|
2018-07-05 10:34:17 +08:00
|
|
|
return read, 0, 0
|
2014-05-15 14:44:19 +08:00
|
|
|
}
|