Home >Backend Development >Golang >How to Concatenate Images in Golang?

How to Concatenate Images in Golang?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 11:14:02759browse

How to Concatenate Images in Golang?

Concatenating Images in Golang

Problem

Although Go provides robust image manipulation capabilities, users often face challenges in creating a single image from multiple smaller ones. Specifically, how can two PNG or JPEG files be concatenated to form a comprehensive image?

Analysis

The provided code reveals the reading of PNG files into an RGBA format:

imgFile, err := os.Open(path)
if err != nil {
    return Image{}, err
}
img, _, err := image.Decode(imgFile)
if err != nil {
    return Image{}, err
}

rgba := image.NewRGBA(img.Bounds())
if rgba.Stride != rgba.Rect.Size().X*4 {
    return Image{}, fmt.Errorf("unsupported stride")
}
draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src)

However, the crux of the issue lies in understanding how to combine multiple RGBA datasets into a single image.

Solution

The solution involves creating a new, empty image (NewRGBA) of sufficient size to accommodate both original images. Subsequently, the Draw method can be employed to overlay each image onto designated portions of the extended image:

// Load two images
imgFile1, err := os.Open("test1.jpg")
if err != nil {
    fmt.Println(err)
}
imgFile2, err := os.Open("test2.jpg")
if err != nil {
    fmt.Println(err)
}
img1, _, err := image.Decode(imgFile1)
if err != nil {
    fmt.Println(err)
}
img2, _, err := image.Decode(imgFile2)
if err != nil {
    fmt.Println(err)
}

// Starting position of the second image
sp2 := image.Point{img1.Bounds().Dx(), 0}

// New rectangle for the second image
r2 := image.Rectangle{sp2, sp2.Add(img2.Bounds().Size())}

// Rectangle for the big image
r := image.Rectangle{image.Point{0, 0}, r2.Max}

// Create a new image
rgba := image.NewRGBA(r)

// Draw the two images
draw.Draw(rgba, img1.Bounds(), img1, image.Point{0, 0}, draw.Src)
draw.Draw(rgba, r2, img2, image.Point{0, 0}, draw.Src)

// Export the 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)

Note: This method preserves the height of the second image. If the first image is taller, it will be cropped.

The above is the detailed content of How to Concatenate Images in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn