Home > Article > Backend Development > How to Combine Multiple Images into One in Go?
How to Combine Images in Go
In Go, you can manipulate images to create a single larger image from multiple smaller ones. To do this, follow the steps below:
For example, to create a horizontal concatenation of two images, you can use the following code:
import ( "fmt" "image" "image/draw" "image/jpeg" "os" ) func main() { // Load the images img1, err := os.Open("test1.jpg") if err != nil { fmt.Println(err) } img2, err := os.Open("test2.jpg") if err != nil { fmt.Println(err) } img1, _, err = image.Decode(img1) if err != nil { fmt.Println(err) } img2, _, err = image.Decode(img2) if err != nil { fmt.Println(err) } // Create the large image r1 := img1.Bounds() r2 := img2.Bounds() r := image.Rectangle{image.Point{0, 0}, r2.Max} rgba := image.NewRGBA(r) // Draw the images draw.Draw(rgba, r1, img1, image.Point{0, 0}, draw.Src) draw.Draw(rgba, r2, img2, image.Point{r1.Dx(), 0}, draw.Src) // Export the final image out, err := os.Create("output.jpg") if err != nil { fmt.Println(err) } var opt jpeg.Options opt.Quality = 80 jpeg.Encode(out, rgba, &opt) }
The above is the detailed content of How to Combine Multiple Images into One in Go?. For more information, please follow other related articles on the PHP Chinese website!