How to add text and annotations to an image in Go?

To add text and annotations to an image in Go, you can use the github.com/fogleman/gg library. Here's an example code snippet to demonstrate the process:

package main import ( "github.com/fogleman/gg" "image" "image/color" "log" ) func main() { // Load the image img, err := gg.LoadImage("image.jpg") if err != nil { log.Fatal(err) } // Create a new drawing context dc := gg.NewContextForImage(img) dc.SetRGB(1, 1, 1) // Set background color to white // Draw the image on the context dc.DrawImage(img, 0, 0) // Set font attributes err = dc.LoadFontFace("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 48) if err != nil { log.Fatal(err) } dc.SetRGB(0, 0, 0) // Set font color to black // Add text to the image dc.DrawStringAnchored("Hello, World!", 100, 100, 0.5, 0.5) // Add annotations to the image dc.SetRGB(1, 0, 0) // Set annotation color to red dc.DrawStringAnchored("Annotation 1", 200, 200, 0.5, 0.5) dc.SetRGB(0, 1, 0) // Set annotation color to green dc.DrawStringAnchored("Annotation 2", 300, 300, 0.5, 0.5) // Save the modified image err = dc.SavePNG("output_image.png") if err != nil { log.Fatal(err) } }

In this example, we first load the image using gg.LoadImage. Then, we create a new drawing context using gg.NewContextForImage. We set the background color to white and draw the loaded image using dc.DrawImage.

Next, we load a font face and set font attributes using dc.LoadFontFace and dc.SetRGB functions. We then use dc.DrawStringAnchored to add text to the image at the specified coordinates. The Anchored method anchors the text to the specified coordinates, and the last two arguments control the alignment of the text.

To add annotations, we simply call dc.DrawStringAnchored again with different text and coordinates, and change the font color to differentiate from the main text.

Finally, we save the modified image using dc.SavePNG.