WhspBrd/pkg/resize_image/resize_image.go
2025-06-02 16:53:32 +02:00

34 lines
793 B
Go

package resize_image
import (
"image"
"image/color"
)
func Resize(img image.RGBA, width int, height int) (*image.RGBA, error) {
if width <= 0 || height <= 0 {
return nil, nil
}
newImg := image.NewRGBA(image.Rect(0, 0, width, height))
scaleX := float64(img.Bounds().Dx()) / float64(width)
scaleY := float64(img.Bounds().Dy()) / 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]
}