亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Alpha 通道(PNG) 和 Golang 的問題

Alpha 通道(PNG) 和 Golang 的問題

Go
喵喔喔 2023-08-07 14:56:54
我在 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.Closeutils.ShowFatalError(err) // Show panic log if err != nil決賽:[ 1 ]如果我使用 jpeg.Decode 而不是 png.Decode 圖像沒有奇怪的顏色。
查看完整描述

2 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

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),
}


查看完整回答
反對 回復 2023-08-07
?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

似乎這個問題也與color.RGBA- 如果我將其與 alpha 一起使用,而不是255在生成的 PNG 中得到奇怪的顏色。在我切換到color.NRGBA(按照接受的答案中的建議)之后,我得到了正確的顏色渲染。

所以不要使用

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

反而

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


查看完整回答
反對 回復 2023-08-07
  • 2 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號