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

How to Concatenate Images in Go?

DDD
Release: 2024-11-07 01:45:03
Original
1027 people have browsed it

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)
}
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template