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/