Golang如何将图像连接/附加到彼此

efe*_*fel 10 graphics png image go

Go具有出色的图像处理和数据库,但是我在从较小的图像创建一个大图像时遇到了麻烦.有没有人知道如何在Golang中获取两个png或jpeg文件并将它们连接起来形成一个包含两个(或更多)文件的大图像?

我正在读这样的png文件:

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)
Run Code Online (Sandbox Code Playgroud)

我对如何获取这个png RGBA数据并与其他RGBA数据连接和/或将其组合成"空"图像感到困惑.

Aru*_*ath 17

创建一个新的空图像(NewRGBA),其边界足以容纳两个图像.然后使用该Draw方法在这个新的大图像的适当部分上绘制每个图像.

以下是代码步骤.

加载两张图片.

imgFile1, err := os.Open("test1.jpg")
imgFile2, err := os.Open("test2.jpg")
if err != nil {
    fmt.Println(err)
}
img1, _, err := image.Decode(imgFile1)
img2, _, err := image.Decode(imgFile2)
if err != nil {
    fmt.Println(err)
}
Run Code Online (Sandbox Code Playgroud)

让我们将第二幅图像绘制到第一张图像的右侧.所以它的出发点应在(w, 0)其中w是所述第一图像的宽度.第一个图像的右下角将是第二个图像的左下角.

//starting position of the second image (bottom left)
sp2 := image.Point{img1.Bounds().Dx(), 0}
Run Code Online (Sandbox Code Playgroud)

它应该是一个足以容纳它的矩形.

//new rectangle for the second image
r2 := image.Rectangle{sp2, sp2.Add(img2.Bounds().Size())}
Run Code Online (Sandbox Code Playgroud)

现在创建一个宽度足以容纳两个图像的大矩形.

//rectangle for the big image
r := image.Rectangle{image.Point{0, 0}, r2.Max}
Run Code Online (Sandbox Code Playgroud)

注意此大图像将具有第二个图像的高度.如果第一张图像较高,则会裁剪.

创建一个新图像.

rgba := image.NewRGBA(r)
Run Code Online (Sandbox Code Playgroud)

现在您可以将这两个图像绘制到这个新图像中

draw.Draw(rgba, img1.Bounds(), img1, image.Point{0, 0}, draw.Src)
draw.Draw(rgba, r2, img2, image.Point{0, 0}, draw.Src)
Run Code Online (Sandbox Code Playgroud)

由于我们在r2第一张图像的右侧创建了它,因此第二张图像将被绘制到右侧.

最后你可以导出它.

out, err := os.Create("./output.jpg")
if err != nil {
    fmt.Println(err)
}

var opt jpeg.Options
opt.Quality = 80

jpeg.Encode(out, rgba, &opt)
Run Code Online (Sandbox Code Playgroud)

  • 我真的很喜欢这个答案,因为它的格式非常好,单独解释了每个部分,简洁,使用了许多现有的 go 功能。 (3认同)

Oza*_*zan 9

我正是为此目的建立了一个图书馆。

您可以按如下方式使用它;

import gim "github.com/ozankasikci/go-image-merge"

grids := []*gim.Grid{
    {ImageFilePath: "test1.jpg"},
    {ImageFilePath: "test2.png"},
}

// merge the images into a 2x1 grid
rgba, err := gim.New(grids, 2, 1).Merge()

// save the output to jpg or png
file, err := os.Create("file/path.jpg|png")
err = jpeg.Encode(file, rgba, &jpeg.Options{Quality: 80})
Run Code Online (Sandbox Code Playgroud)

https://github.com/ozankasikci/go-image-merge


Pie*_*Pah 8

如果你在函数中做了一些事情并创建一个结构来理解每个像素,你的生活会容易得多.

// Create a struct to deal with pixel
type Pixel struct {
    Point image.Point
    Color color.Color
}

// Keep it DRY so don't have to repeat opening file and decode
func OpenAndDecode(filepath string) (image.Image, string, error) {
    imgFile, err := os.Open(filepath)
    if err != nil {
        panic(err)
    }
    defer imgFile.Close()
    img, format, err := image.Decode(imgFile)
    if err != nil {
        panic(err)
    }
    return img, format, nil
}

// Decode image.Image's pixel data into []*Pixel
func DecodePixelsFromImage(img image.Image, offsetX, offsetY int) []*Pixel {
    pixels := []*Pixel{}
    for y := 0; y <= img.Bounds().Max.Y; y++ {
        for x := 0; x <= img.Bounds().Max.X; x++ {
            p := &Pixel{
                Point: image.Point{x + offsetX, y + offsetY},
                Color: img.At(x, y),
            }
            pixels = append(pixels, p)
        }
    }
    return pixels
}

func main() {
    img1, _, err := OpenAndDecode("makey.png")
    if err != nil {
        panic(err)
    }
    img2, _, err := OpenAndDecode("sample.jpg")
    if err != nil {
        panic(err)
    }
    // collect pixel data from each image
    pixels1 := DecodePixelsFromImage(img1, 0, 0)
    // the second image has a Y-offset of img1's max Y (appended at bottom)
    pixels2 := DecodePixelsFromImage(img2, 0, img1.Bounds().Max.Y)
    pixelSum := append(pixels1, pixels2...)

    // Set a new size for the new image equal to the max width
    // of bigger image and max height of two images combined
    newRect := image.Rectangle{
        Min: img1.Bounds().Min,
        Max: image.Point{
            X: img2.Bounds().Max.X,
            Y: img2.Bounds().Max.Y + img1.Bounds().Max.Y,
        },
    }
    finImage := image.NewRGBA(newRect)
    // This is the cool part, all you have to do is loop through
    // each Pixel and set the image's color on the go
    for _, px := range pixelSum {
            finImage.Set(
                px.Point.X,
                px.Point.Y,
                px.Color,
            )
    }
    draw.Draw(finImage, finImage.Bounds(), finImage, image.Point{0, 0}, draw.Src)

    // Create a new file and write to it
    out, err := os.Create("./output.png")
    if err != nil {
        panic(err)
        os.Exit(1)
    }
    err = png.Encode(out, finImage)
    if err != nil {
        panic(err)
        os.Exit(1)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 很多工作都进入了这个答案,我也喜欢它.非常模块化. (3认同)