gpt4 book ai didi

image - 在 Go 中合并多个图像

转载 作者:IT王子 更新时间:2023-10-29 01:53:39 24 4
gpt4 key购买 nike

我正在尝试用 Go 合并一个包含 N 个图像的数组(其中 N 将是一个动态值),但结果总是得到一个黑色图像。

这是我的代码:

package main

import (
"image"
"image/draw"
"image/jpeg"
"image/png"
"log"
"os"
)

func openAndDecode(imgPath string) image.Image {
img, err := os.Open(imgPath)
if err != nil {
log.Fatalf("Failed to open %s", err)
}

decoded, err := png.Decode(img)
if err != nil {
log.Fatalf("Failed to decode %s", err)
}
defer img.Close()

return decoded
}

func main () {
var images = [4]string{"background", "shadow", "item1 ", "item2"}
var decodedImages = [4]*image.RGBA{}

for i, img := range images {
decodedImage := openAndDecode("./imgs/" + img + ".png")
bounds := decodedImage.Bounds()
newImg := image.NewRGBA(bounds)
decodedImages[i] = newImg
}

bounds := decodedImages[0].Bounds()
newImage := image.NewRGBA(bounds)

for _, img := range decodedImages {
draw.Draw(newImage, img.Bounds(), img, image.ZP, draw.Src)
}

result, err := os.Create("result.jpg")
if err != nil {
log.Fatalf("Failed to create: %s", err)
}

jpeg.Encode(result, newImage, &jpeg.Options{jpeg.DefaultQuality})
defer result.Close()
}

我是 Go 的新手,我找不到我哪里错了。

最佳答案

在加载图像的第一个循环中,您还创建了一个新的空图像,并将这个空图像存储在 decodedImages 中。然后迭代这些空图像并将它们组合起来。

相反,您应该将加载的图像存储在 decodedImages 中:

for i, img := range images {
decodedImages[i] = openAndDecode("./imgs/" + img + ".png")
}

为此,声明 decodedImagesimage.Image 的一部分(因为 openAndDecode() 返回类型 图像.图像):

var decodedImages = make([]image.Image, len(images))

此外,每当您打开一个文件并检查错误时,您应该立即延迟关闭它,这样如果后续代码失败,该文件仍会关闭。

此外,要将图像与 alpha channel “组合”,您还应该使用 draw.Over 运算符。引用博文:The Go Blog: The Go image/draw package :

The Over operator performs the natural layering of a source image over a destination image: the change to the destination image is smaller where the source (after masking) is more transparent (that is, has lower alpha). The Src operator merely copies the source (after masking) with no regard for the destination image's original content. For fully opaque source and mask images, the two operators produce the same output, but the Src operator is usually faster.

关于image - 在 Go 中合并多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com