2014-05-14 23:44:19 -07:00
|
|
|
package images
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"image"
|
|
|
|
"image/gif"
|
|
|
|
"image/jpeg"
|
|
|
|
"image/png"
|
2020-03-21 22:16:00 -07:00
|
|
|
"io"
|
2014-10-26 11:34:55 -07:00
|
|
|
|
2024-04-25 02:16:04 -04:00
|
|
|
"github.com/cognusion/imaging"
|
2020-03-21 22:16:00 -07:00
|
|
|
|
2022-07-29 00:17:28 -07:00
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
2021-07-24 14:26:40 +09:00
|
|
|
|
|
|
|
_ "golang.org/x/image/webp"
|
2014-05-14 23:44:19 -07: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-14 23:44:19 -07:00
|
|
|
if width == 0 && height == 0 {
|
2018-07-05 10:34:17 +08:00
|
|
|
return read, 0, 0
|
2014-05-14 23:44:19 -07: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-14 23:44:19 -07:00
|
|
|
bounds := srcImage.Bounds()
|
|
|
|
var dstImage *image.NRGBA
|
2014-07-05 00:43:41 -07:00
|
|
|
if bounds.Dx() > width && width != 0 || bounds.Dy() > height && height != 0 {
|
2017-05-05 12:17:30 +03: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 00:43:41 -07:00
|
|
|
}
|
2014-07-20 23:12:49 -07:00
|
|
|
} else {
|
2020-03-21 22:16:00 -07:00
|
|
|
read.Seek(0, 0)
|
2018-07-05 10:34:17 +08:00
|
|
|
return read, bounds.Dx(), bounds.Dy()
|
2014-05-14 23:44:19 -07:00
|
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
|
|
switch ext {
|
|
|
|
case ".png":
|
|
|
|
png.Encode(&buf, dstImage)
|
2014-07-04 18:03:48 -07:00
|
|
|
case ".jpg", ".jpeg":
|
2014-05-14 23:44:19 -07:00
|
|
|
jpeg.Encode(&buf, dstImage, nil)
|
|
|
|
case ".gif":
|
|
|
|
gif.Encode(&buf, dstImage, nil)
|
2021-07-24 14:26:40 +09:00
|
|
|
case ".webp":
|
|
|
|
// Webp does not have golang encoder.
|
|
|
|
png.Encode(&buf, dstImage)
|
2014-05-14 23:44:19 -07: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-14 23:44:19 -07:00
|
|
|
}
|
2018-07-05 10:34:17 +08:00
|
|
|
return read, 0, 0
|
2014-05-14 23:44:19 -07:00
|
|
|
}
|