首页  >  文章  >  后端开发  >  Go 是否有可以打开 2 位颜色深度的调色板 png 的库?

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

PHPz
PHPz转载
2024-02-09 23:30:21331浏览

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删除