resource_manager/image/image.go

53 lines
1.1 KiB
Go
Raw Normal View History

2022-06-13 06:37:16 +00:00
package image
import (
"bytes"
"github.com/anthonynsimon/bild/transform"
"image"
"image/jpeg"
"io"
)
func ResizeImage(imageBytes []byte, minWidth, minHeight int) ([]byte, error) {
img, _, err := image.Decode(bytes.NewReader(imageBytes))
if err != nil {
return nil, err
}
var buffer bytes.Buffer
writer := io.Writer(&buffer)
rX, rY := Resize(minWidth, minHeight, img.Bounds().Dx(), img.Bounds().Dy())
img = transform.Resize(img, rX, rY, transform.Gaussian)
if err = jpeg.Encode(writer, img, nil); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func Resize(minX, minY, x, y int) (int, int) {
return resize(float32(minX), float32(minY), float32(x), float32(y))
}
func resize(minX, minY, x, y float32) (int, int) {
if x <= minX && y <= minY {
return int(x), int(y)
}
// try by width
rX := minX
rY := y * (rX / x)
if rX >= minX && rY >= minY && rX <= x && rY <= y {
return int(rX), int(rY)
}
// try by height
rY = minY
rX = x * (rY / y)
if rX >= minX && rY >= minY && rX <= x && rY <= y {
return int(rX), int(rY)
}
return int(x), int(y)
}