How to overlay one image onto another image in Go?

To overlay one image onto another image in Go, you can use the draw package from the Go standard library. Here's an example of how you can do it:

package main import ( "fmt" "image" "image/draw" "image/jpeg" "os" ) func main() { // Open the two images backgroundImageFile, err := os.Open("background.jpg") if err != nil { fmt.Println("Error opening background image:", err) return } defer backgroundImageFile.Close() backgroundImage, err := jpeg.Decode(backgroundImageFile) if err != nil { fmt.Println("Error decoding background image:", err) return } overlayImageFile, err := os.Open("overlay.png") if err != nil { fmt.Println("Error opening overlay image:", err) return } defer overlayImageFile.Close() overlayImage, err := jpeg.Decode(overlayImageFile) if err != nil { fmt.Println("Error decoding overlay image:", err) return } // Create a new image with the size of the background image mergedImage := image.NewRGBA(backgroundImage.Bounds()) // Draw the background image onto the new image draw.Draw(mergedImage, mergedImage.Bounds(), backgroundImage, image.ZP, draw.Src) // Overlay the overlay image onto the merged image draw.Draw(mergedImage, overlayImage.Bounds(), overlayImage, image.ZP, draw.Over) // Save the merged image to a file mergedImageFile, err := os.Create("merged.jpg") if err != nil { fmt.Println("Error creating merged image file:", err) return } defer mergedImageFile.Close() jpeg.Encode(mergedImageFile, mergedImage, nil) fmt.Println("Images merged successfully.") }

Make sure to replace "background.jpg", "overlay.png", and "merged.jpg" with the paths to your actual background image, overlay image, and the desired output file name.

This code opens the background image and overlay image files using the os.Open function, decodes them into image.Image objects using the appropriate Decode function (jpeg.Decode in this case), creates a new RGBA image with the same size as the background image using image.NewRGBA, draws the background image onto the new image using draw.Draw with the Src operation, and finally overlays the overlay image onto the merged image using draw.Draw with the Over operation.

The merged image is then saved to a file using jpeg.Encode.