代码之家  ›  专栏  ›  技术社区  ›  cassm

无法将颜色数组用作颜色。图像参数中的调色板值。新苍白

go
  •  0
  • cassm  · 技术社区  · 11 月前

    我目前正在尝试使用从已知尺寸的png文件的第一行读取的调色板创建一个图像。我通过宣布 Color 使用已知大小的数组,然后单独设置该数组中的条目,然后将该数组传递给 image.NewPaletted 作为调色板参数。我从Donovan&克尼汉:

    var palette = []color.Color{color.White, color.Black}
    rect := image.Rect(0, 0, 200, 200)
    img := image.NewPaletted(rect, palette)
    

    …但以下内容在我的代码中不起作用(我检查了 os.Open png.Decode 但为了简洁起见省略了这一点):

    file, _ := os.Open("palette.png")
    img, _ := png.Decode(file)
    
    // image width is guaranteed to == paletteSize
    var palette [paletteSize]color.Color
    for i := range(paletteSize) {
        palette[i] = img.At(i, 0)
    }
    
    rect := image.Rect(0, 0, 200, 200)
    img := image.NewPaletted(rect, palette)
    

    它失败了 cannot use palette (variable of type [256]color.Color) as color.Palette value in argument to image.NewPaletted 值得注意的是, the docs 表明这一点 color.Palette 定义为 type Palette []Color .

    感觉这两个数组应该是等价的,因为它们的大小都是已知的,只是初始化方式不同,但很明显我遗漏了一些东西。我试着减少 paletteSize 如果减小到2,它仍然会抛出相同的错误,所以我认为这不是数组大小的问题。有人知道我做错了什么吗?

    1 回复  |  直到 11 月前
        1
  •  1
  •   Brits    11 月前

    [256]color.Color 是一个 array ,而 color.Palette 定义为 type Palette []Color ,a也是 slice 。这意味着您正试图将数组传递给需要切片的函数;错误是让您知道这不受支持。

    你有几个选择;最小的改变就是使用 image.NewPaletted(rect, palette[:]) (这将使用数组作为底层缓冲区创建一个切片 ref ). 或者,你可以只使用一个切片:

    func main() {
        file, _ := os.Open("palette.png")
        img, _ := png.Decode(file)
    
        paletteSize:= 256
        palette := make([]color.Color, paletteSize)
        for i := range paletteSize {
            palette[i] = img.At(i, 0)
        }
    
        rect := image.Rect(0, 0, 200, 200)
        _ = image.NewPaletted(rect, palette)
    }