Implemented resizer

This commit is contained in:
Borna Rajković committed 2022-06-13 08:37:16 +02:00
1 parent bceaa3b6df
commit a5d41ae1f7
11 files changed
+148 -640

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
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)
}
+31
View File
@@ -0,0 +1,31 @@
package image_test
import (
"git.bbr-dev.info/brajkovic/resource_manager/image"
"testing"
)
func TestResize(t *testing.T) {
cases := [][]int{
// minX, minY, x, y, newX, newY
{400, 300, 400, 800, 400, 800},
{400, 300, 800, 400, 600, 300},
{1024, 1280, 800, 400, 800, 400},
{400, 300, 800, 100, 800, 100},
{1200, 900, 1600, 1400, 1200, 1050},
}
for _, testCase := range cases {
minX, minY, x, y, newX, newY := destructure(testCase)
rX, rY := image.Resize(minX, minY, x, y)
if rX != newX || rY != newY {
t.Errorf("for (%d, %d, %d, %d)expected (%d, %d) received (%d, %d)", minX, minY, x, y, newX, newY, rX, rY)
}
}
}
func destructure(testCase []int) (minX, minY, x, y, newX, newY int) {
return testCase[0], testCase[1], testCase[2], testCase[3], testCase[4], testCase[5]
}