首頁  >  文章  >  後端開發  >  Go 是否有可以開啟 2 位元色彩深度的調色盤 png 的函式庫?

Go 是否有可以開啟 2 位元色彩深度的調色盤 png 的函式庫?

PHPz
PHPz轉載
2024-02-09 23:30:21333瀏覽

Go 是否有可以打开 2 位颜色深度的调色板 png 的库?

php小編西瓜Go是一種強大的程式語言,但是否有可以開啟2位元顏色深度的調色盤PNG的函式庫呢?答案是肯定的。 Go語言有許多函式庫和工具可用於處理影像,其中一些可以開啟並處理特定深度的調色板PNG影像。透過使用這些庫,您可以輕鬆地讀取和編輯2位元顏色深度的調色板PNG圖像,為您的應用程式添加更多的功能和靈活性。無論您是初學者還是有經驗的Go開發人員,這些程式庫都可以幫助您實現您的目標,提供更好的影像處理和編輯能力。

問題內容

如何使用 go 讀取基於調色板的 png 映像?

對於 python 中的映像,我可以簡單地執行以下操作:

from pil import image

im = image.open('image.png')
pix = im.load()
for i in range(100):
    for j in range(100):
        print(pix[i, j])

使用go:

f, err := os.open("image.png")
    if err != nil {
        log.fatal(err)
    }
    defer f.close()

    pal, ok := cfg.colormodel.(color.palette) // ok is true
    if ok {
        for i := range pal {
            cr, cg, cb, ca := pal[i].rgba()
            fmt.printf("pal[%3d] = %5d,%5d,%5d,%5d\n", i, cr, cg, cb, ca)
        }
    }

    img, err := png.decode(f)
    if err != nil {
        log.fatal(err) // fails here!!
    }

    for y := img.bounds().min.y; y < img.bounds().max.y; y++ {
        for x := img.bounds().min.x; x < img.bounds().max.x; x++ {
            log.println("img.at(x, y):", img.at(x, y))
        }
        fmt.print("\n")
    }

解碼時會拋出「png:無效格式:不是 png 檔案」。

如果我在 mac shell 上使用 file 指令,它會顯示:

image.png: png image data, 100 x 100, 2-bit colormap, non-interlaced

vscode 渲染圖像效果很好。

我在由 adob​​e illustrator 創建的圖像和由以下程式碼生成的圖像上都進行了嘗試。兩者都遇到相同的錯誤:

func createPNG() {
    // Create a new image with the desired dimensions
    img := image.NewPaletted(image.Rect(0, 0, 100, 100), color.Palette{
        color.RGBA{255, 0, 0, 255}, // Red
        color.RGBA{0, 255, 0, 255}, // Green
        color.RGBA{0, 0, 255, 255}, // Blue
    })

    // Set the pixel colors in the image
    for x := 0; x < 100; x++ {
        for y := 0; y < 100; y++ {
            switch {
            case x < 50 && y < 50:
                img.SetColorIndex(x, y, 0) // Set the pixel at (x, y) to red
            case x >= 50 && y < 50:
                img.SetColorIndex(x, y, 1) // Set the pixel at (x, y) to green
            case x < 50 && y >= 50:
                img.SetColorIndex(x, y, 2) // Set the pixel at (x, y) to blue
            default:
                img.SetColorIndex(x, y, 3) // Set the pixel at (x, y) to transparent
            }
        }
    }

    // Create a new file to save the PNG image
    file, err := os.Create("image.png")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // Encode the image as a PNG and save it to the file
    err = png.Encode(file, img)
    if err != nil {
        panic(err)
    }
}

解決方法

您的情況似乎不是圖像的格式,而是您使用圖像檔案的方式。

我假設您首先將其傳遞給image.DecodeConfig() (程式碼沒有顯示它,但cfg 必須已初始化),然後傳遞給image.Decode ()

問題是,在第一次呼叫之後,您的檔案有一個偏移量,但第二次呼叫假定它是從檔案的開頭讀取。

您可以透過在讀取配置後回滾檔案來解決此問題:

檔.Seek(0, io.SeekStart)

以上是Go 是否有可以開啟 2 位元色彩深度的調色盤 png 的函式庫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除