WhspBrd/pkg/resize_image/resize_image.go
2025-06-02 18:39:50 +02:00

41 lines
1.0 KiB
Go

package resize_image
import (
"image"
"image/color"
)
func Resize(img image.RGBA, width int, height int) (*image.RGBA, error) {
originalWidth := img.Bounds().Dx()
originalHeight := img.Bounds().Dy()
if width <= 0 && height <= 0 {
return nil, nil
} else if width <= 0 {
width = int(float64(height) * float64(originalWidth) / float64(originalHeight))
} else if height <= 0 {
height = int(float64(width) * float64(originalHeight) / float64(originalWidth))
}
newImg := image.NewRGBA(image.Rect(0, 0, width, height))
scaleX := float64(originalWidth) / float64(width)
scaleY := float64(originalHeight) / float64(height)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
srcX := int(float64(x) * scaleX)
srcY := int(float64(y) * scaleY)
r, g, b, a := getPixel(img, srcX, srcY)
newImg.Set(x, y, color.RGBA{r, g, b, a})
}
}
return newImg, nil
}
func getPixel(img image.RGBA, x int, y int) (uint8, uint8, uint8, uint8) {
index := img.PixOffset(x, y)
return img.Pix[index], img.Pix[index+1], img.Pix[index+2], img.Pix[index+3]
}