How to rotate an image by a certain angle in Go?

To rotate an image by a certain angle in Go, you can use the golang.org/x/image/draw package. Follow the steps below:

  1. Import the necessary packages:
import ( "image" "image/draw" "golang.org/x/image/math/fixed" "golang.org/x/image/vector" )
  1. Create a new draw.Image from the original image:
originalImg, _ := // load the original image originalBounds := originalImg.Bounds() rotatedImg := image.NewRGBA(originalBounds)
  1. Create a draw.Context using the rotatedImg:
rotatedCtx := draw.NewContext(rotatedImg, originalBounds)
  1. Define the rotation angle in radians:
angle := // specify the angle in radians
  1. Calculate the center point of the original image:
center := fixed.Point26_6{ X: fixed.Int26_6(originalBounds.Dx() / 2), Y: fixed.Int26_6(originalBounds.Dy() / 2), }
  1. Use a 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)
  1. Draw the rotated image onto the rotatedCtx:
rotatedCtx.DrawImage(originalBounds, originalImg, originalBounds.Min, draw.Src)
  1. Use the 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.