Concatenating multiple images into a single, larger image is a common scenario in image processing. In Go, achieving this is straightforward using the image package.
First, create a new image with dimensions large enough to accommodate all the smaller images.
newImage := image.NewRGBA(image.Rect(0, 0, totalWidth, maxHeight))
Here, totalWidth is the combined width of the smaller images, and maxHeight is the maximum height among them.
Next, draw each smaller image onto the new image. Determine the appropriate starting point and rectangle for each image.
for _, img := range smallerImages { offset := point{dx, 0} // offset of the current image r := img.Bounds() // rectangle of the smaller image newImage.Draw(image.Rect(offset.X, offset.Y, offset.X+r.Dx(), offset.Y+r.Dy()), img, r.Min, draw.Src) dx += r.Dx() // update the x coordinate for the next image }
Finally, export the concatenated image to a file or stream.
out, err := os.Create("output.png") if err != nil { return err } if err := png.Encode(out, newImage); err != nil { return err }
The above is the detailed content of How can I concatenate multiple images into a single image using the Go image package?. For more information, please follow other related articles on the PHP Chinese website!