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 && y < 50:
img.SetColorIndex(x, y, 1) // Set the pixel at (x, y) to green
case x = 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)






