how to read a png file in color and output as gray scale using the Go programming language?

mlbright picture mlbright · Jan 2, 2012 · Viewed 14k times · Source

How do I read in a color .png file in the Go programming language, and output it as an 8-bit grayscale image?

Answer

Evan Shaw picture Evan Shaw · Jan 2, 2012

The program below takes an input file name and an output file name. It opens the input file, decodes it, converts it to grayscale, then encodes it to the output file.

Thie program isn't specific to PNGs, but to support other file formats you'd have to import the correct image package. For example, to add JPEG support you could add to the imports list _ "image/jpeg".

If you only want to support PNG, then you can use image/png.Decode directly instead of 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)
}