go - Alpha channel (PNG) 和 Golang 的问题

标签 go png

我在 golang 中的图像遇到了一个简单的问题。我正在用颜色绘制 png 图像,但结果不是我想要的。

在 Alpha 值最低的像素中,绘制另一种颜色。我正在使用 alphaChannel = false

/* return new image with new color
 * alphaChannel = true get AlphaChannel from given color
 * alphaChannel = false get AlphaChannel from image (x,y) point
 */
func PaintPngImage(img image.Image, cl color.Color, alphaChannel bool) image.Image {
    R, G, B, A := cl.RGBA()
    composeImage := image.NewRGBA(img.Bounds())

    // paint image over a new image
    draw.Draw(composeImage, composeImage.Bounds(), img, image.Point{}, draw.Over)

    // paint new color over the image
    bounds := composeImage.Bounds()
    w, h := bounds.Max.X, bounds.Max.Y

    for x := 0; x < w; x++ {
        for y := 0; y < h; y++ {
            _, _, _, aa := composeImage.At(x, y).RGBA()
            if !alphaChannel {
                A = aa
            }
            realColor := color.RGBA{R: uint8(R),G: uint8(G),B: uint8(B),A: uint8(A)}
            if aa != 0 {
                composeImage.Set(x, y, realColor)
            }
        }
    }

    return composeImage
}

colorLayer := PaintPngImage(layerImage, cl, false)
out, err := os.Create("./output/test.png")
utils.ShowFatalError(err)
err = png.Encode(out, colorLayer)
utils.CloseFile(out) // close file os.Close
utils.ShowFatalError(err) // Show panic log if err != nil

决赛:[1 ]

如果我使用 jpeg.Decode 而不是 png.Decode 图像没有奇怪的颜色。

最佳答案

Color.RGBA()返回 0..0xffff 范围内的颜色分量,而不是 0..0xff 范围内的颜色分量:

// RGBA returns the alpha-premultiplied red, green, blue and alpha values
// for the color. Each value ranges within [0, 0xffff], but is represented
// by a uint32 so that multiplying by a blend factor up to 0xffff will not
// overflow.

因此,在构造要绘制的颜色时,您必须右移所有 16 位分量(按 8),而不仅仅是转换为 uint8,因为该转换会保留最低 8 位,这可能是“随机”与 16 位值相比,您需要较高的 8 位:

realColor := color.RGBA{
    R: uint8(R>>8),
    G: uint8(G>>8),
    B: uint8(B>>8),
    A: uint8(A>>8),
}

关于go - Alpha channel (PNG) 和 Golang 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59046618/

相关文章:

python - matplotlib savefig 性能,在循环中保存多个 png

go - 在 go lang 中将字符串转换为 uint

go - 从 Golang 应用程序使用 GraphQL 服务

go - 测试函数是否被调用

css - 带有 CSS 和 PNG 的假字体图标

CgBI 图像到 RGBA 的 Java 转换器?

c++ - 在 SDL 中显示 PNG?

python - 如何从 Python Azure 存储下载 Blob 图像并从中创建图像对象?

google-app-engine - 如何判断我是否在 google app engine/go 上本地运行

go - 编译器时间码 block