"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Concatenate Images in Go?

How to Concatenate Images in Go?

Published on 2024-11-09
Browse:939

How to Concatenate Images in Go?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3