Concatenate Images in Go: A Comprehensive Guide
In Go, manipulating images is a breeze thanks to its powerful image libraries. However, if you want to merge multiple images into one large canvas, things can get confusing. Here's a step-by-step guide to handle this task like a pro.
Loading Images
To kick things off, load the images you wish to concatenate. Here's a code snippet to do that:
// Open the first image imgFile1, err := os.Open("test1.jpg") if err != nil { fmt.Println(err) } // Decode the image img1, _, err := image.Decode(imgFile1) if err != nil { fmt.Println(err) } // Open the second image imgFile2, err := os.Open("test2.jpg") if err != nil { fmt.Println(err) } // Decode the image img2, _, err := image.Decode(imgFile2) if err != nil { fmt.Println(err) }
Creating a New Image
Next, let's create a spacious new image to accommodate both loaded images. Determine the dimensions of this new canvas by adding the widths of both images:
r := image.Rectangle{image.Point{0, 0}, img1.Bounds().Dx() + img2.Bounds().Dx(), img1.Bounds().Dy()} rgba := image.NewRGBA(r)
Drawing the Images
Now comes the fun part: assembling the images within this new canvas. Determine the position where you want to place the second image, and then draw both images onto the canvas:
// Starting point of the second image (bottom left) sp2 := image.Point{img1.Bounds().Dx(), 0} // Rectangle for the second image r2 := image.Rectangle{sp2, sp2.Add(img2.Bounds().Size())} // Draw the first image draw.Draw(rgba, img1.Bounds(), img1, image.Point{0, 0}, draw.Src) // Draw the second image draw.Draw(rgba, r2, img2, image.Point{0, 0}, draw.Src)
Saving the Result
Finally, let's immortalize this concatenated masterpiece by saving it as a new image file:
out, err := os.Create("./output.jpg") if err != nil { fmt.Println(err) } var opt jpeg.Options opt.Quality = 80 jpeg.Encode(out, rgba, &opt)
That's it! You've successfully merged multiple images into a cohesive whole. Go forth and conquer the world of image manipulation.
The above is the detailed content of How to Concatenate Images in Go?. For more information, please follow other related articles on the PHP Chinese website!