在Golang中,当像素值携带alpha值时,会导致颜色值发生变化。我在python中尝试了相同的代码。没问题!
这是Golang脚本:
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脚本:
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)
为什么戈朗的结果会发生变化?
发布于 2021-09-18 07:21:23
color.RGBA
表示α乘乘颜色.对于预乘颜色,alpha分量表示R/G/B分量可取的最大值。因此,color.RGBA{122,122,122,122}
用alpha 122表示白色。
png.Decode
返回一个没有预乘的image.NRGBA
。当显示像素类型时,这就更清楚了。例:
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
Before: color.NRGBA: {55 23 14 122}
After: color.NRGBA: {55 23 14 122}
https://stackoverflow.com/questions/69232239
复制相似问题