首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么Golang `png.Encode`方法使颜色数据错误?

为什么Golang `png.Encode`方法使颜色数据错误?
EN

Stack Overflow用户
提问于 2021-09-18 06:39:33
回答 1查看 298关注 0票数 0

在Golang中,当像素值携带alpha值时,会导致颜色值发生变化。我在python中尝试了相同的代码。没问题!

这是Golang脚本:

代码语言:javascript
运行
复制
newRgba := image.NewRGBA(image.Rect(0, 0, 1, 1)) //new image
newRgba.SetRGBA(0, 0, color.RGBA{R: 55, G: 23, B: 14, A: 122}) // set pixel value
f, _ := os.Create("./save.png")
defer f.Close()
// save image
png.Encode(f, newRgba)


ff, _ := ioutil.ReadFile("./save.png") //read image
bbb := bytes.NewBuffer(ff)
m, _, _ := image.Decode(bbb)
R, G, B, A := m.At(0, 0).RGBA()
fmt.Println(R>>8,
    G>>8,
    B>>8,
    A>>8,
) // get {55 23 13 122} , it is wrong! Why not {55 23 14 122} ?

这是python脚本:

代码语言:javascript
运行
复制
from PIL import Image
img = Image.new('RGBA', (1, 1), (55, 23, 14,122)) # set pixel value
img.save('bg.png')


im = Image.open('bg.png')
pix = im.load()

print(pix[0,0])  // get (55, 23, 14, 122)

为什么戈朗的结果会发生变化?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-18 07:21:23

color.RGBA表示α乘乘颜色.对于预乘颜色,alpha分量表示R/G/B分量可取的最大值。因此,color.RGBA{122,122,122,122}用alpha 122表示白色。

png.Decode返回一个没有预乘的image.NRGBA。当显示像素类型时,这就更清楚了。例:

代码语言:javascript
运行
复制
fmt.Printf("%#v\n", m.At(0, 0))
// color.NRGBA{R:0xff, G:0xff, B:0xff, A:0x7a}

在使用NRGBA类型时,您的示例将有效。

参见这个正在运行的示例:https://play.golang.org/p/69bvYQfkCA_P

代码语言:javascript
运行
复制
Before: color.NRGBA: {55 23 14 122}
After:  color.NRGBA: {55 23 14 122}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69232239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档