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

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.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵