douyi0219
2019-01-22 13:09
浏览 449
已采纳

Golang使RGBA图像显示奇怪的颜色

So I'm making some rgba images pixel by pixel following a certain pattern and saving them as png later on and noticed that when alpha channel es changed with certain colors it changes the whole pixel color when stored as png.

I made a test to show what is currently happening:

    img := image.NewRGBA(image.Rect(0, 0, 250, 250))
    for y := 0; y < height; y++ {
        for x := 0; x < width; x++ {
            f.Read(b)
            img.SetRGBA(x, y, color.RGBA{
                249,
                214,
                133,
                255,
            })
        }
    }
    var buff bytes.Buffer
    err := png.Encode(&buff, img)
    if err != nil {
        log.Println(err)
        return
    }

This will print an image of color #F9D685. But if I change alpha into 200 it will print another one with #6844BC and transparency instead of printing the original color with it's transparency.

Is there a way to solve this? I believe that it's because I'm missing something but can't really figure it out and didn't find anything similar to what's happening to me on google/here.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyinyi7766 2019-01-22 13:17
    已采纳

    That one is simple:

    go doc color.RGBA
    

    package color // import "image/color"

    type RGBA struct {
        R, G, B, A uint8
    }
    

    RGBA represents a traditional 32-bit alpha-premultiplied color, having 8 bits for each of red, green, blue and alpha.

    An alpha-premultiplied color component C has been scaled by alpha (A), so has valid values 0 <= C <= A.

    You might be looking for color.NRGBA.

    (Always, really always, consult the documentation of the involved types and functions. Always.)

    点赞 评论

相关推荐 更多相似问题