To rotate an image by a certain angle in Go, you can use the golang.org/x/image/draw
package. Follow the steps below:
import (
"image"
"image/draw"
"golang.org/x/image/math/fixed"
"golang.org/x/image/vector"
)
draw.Image
from the original image:originalImg, _ := // load the original image
originalBounds := originalImg.Bounds()
rotatedImg := image.NewRGBA(originalBounds)
draw.Context
using the rotatedImg
:rotatedCtx := draw.NewContext(rotatedImg, originalBounds)
angle := // specify the angle in radians
center := fixed.Point26_6{
X: fixed.Int26_6(originalBounds.Dx() / 2),
Y: fixed.Int26_6(originalBounds.Dy() / 2),
}
vector.Affine2D
to rotate the image:matrix := vector.NewMatrix()
matrix = matrix.Translate(center.X, center.Y)
matrix = matrix.Rotate(angle)
matrix = matrix.Translate(-center.X, -center.Y)
rotatedCtx.SetTransform(matrix)
rotatedCtx
:rotatedCtx.DrawImage(originalBounds, originalImg, originalBounds.Min, draw.Src)
rotatedImg
as the output image.Here's an example of how you can rotate an image by 45 degrees:
package main
import (
"image"
"image/draw"
"log"
"os"
"golang.org/x/image/math/fixed"
"golang.org/x/image/vector"
)
func main() {
// Load the original image
file, err := os.Open("input.png")
if err != nil {
log.Fatal(err)
}
defer file.Close()
originalImg, _, err := image.Decode(file)
if err != nil {
log.Fatal(err)
}
originalBounds := originalImg.Bounds()
rotatedImg := image.NewRGBA(originalBounds)
rotatedCtx := draw.NewContext(rotatedImg, originalBounds)
angle := 45.0 * (3.14159 / 180.0) // Convert degrees to radians
center := fixed.Point26_6{
X: fixed.Int26_6(originalBounds.Dx() / 2),
Y: fixed.Int26_6(originalBounds.Dy() / 2),
}
matrix := vector.NewMatrix()
matrix = matrix.Translate(center.X, center.Y)
matrix = matrix.Rotate(angle)
matrix = matrix.Translate(-center.X, -center.Y)
rotatedCtx.SetTransform(matrix)
rotatedCtx.DrawImage(originalBounds, originalImg, originalBounds.Min, draw.Src)
// Save the rotated image
outFile, err := os.Create("output.png")
if err != nil {
log.Fatal(err)
}
defer outFile.Close()
err = png.Encode(outFile, rotatedImg)
if err != nil {
log.Fatal(err)
}
}
Make sure to replace "input.png"
with the path to your input image, and "output.png"
with the desired path for the output image.