image - 如何使用Go编程语言读取彩色png文件并输出为灰度?

标签 image png go grayscale

Go编程语言如何读入彩色.png文件,输出为8位灰度图?

最佳答案

下面的程序有一个输入文件名和一个输出文件名。它打开输入文件,对其进行解码,将其转换为灰度,然后将其编码为输出文件。

该程序并非特定于 PNG,但要支持其他文件格式,您必须导入正确的图像包。例如,要添加 JPEG 支持,您可以将 _ "image/jpeg" 添加到导入列表中。

如果你想支持PNG,那么你可以使用image/png.Decode直接代替 image.Decode .

package main

import (
    "image"
    "image/png" // register the PNG format with the image package
    "os"
)

func main() {
    infile, err := os.Open(os.Args[1])
    if err != nil {
        // replace this with real error handling
        panic(err.String())
    }
    defer infile.Close()

    // Decode will figure out what type of image is in the file on its own.
    // We just have to be sure all the image packages we want are imported.
    src, _, err := image.Decode(infile)
    if err != nil {
        // replace this with real error handling
        panic(err.String())
    }

    // Create a new grayscale image
    bounds := src.Bounds()
    w, h := bounds.Max.X, bounds.Max.Y
    gray := image.NewGray(w, h)
    for x := 0; x < w; x++ {
        for y := 0; y < h; y++ {
            oldColor := src.At(x, y)
            grayColor := image.GrayColorModel.Convert(oldColor)
            gray.Set(x, y, grayColor)
        }
    }

    // Encode the grayscale image to the output file
    outfile, err := os.Create(os.Args[2])
    if err != nil {
        // replace this with real error handling
        panic(err.String())
    }
    defer outfile.Close()
    png.Encode(outfile, gray)
}

关于image - 如何使用Go编程语言读取彩色png文件并输出为灰度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8697095/

相关文章:

.net - 如何确定一个文件是否是.NET 中的图像文件?

Javascript:用数组中的图像填充表格

javascript - 使用 Javascript 减少 base64 图像内存大小

html - 如何在不将图像推到另一行的情况下缩放图像

java - PDF框PNG图像不支持

CgBI 图像到 RGBA 的 Java 转换器?

twitter - 将 Twitter 与 Golang 结合使用时出错

css - 将什么代码添加到 CSS 以使 Firefox 读取具有透明背景的 PNG 图像

html - 如何从请求对象中获取提交值

json - 你如何在 Go 中解码为正确的顺序?