Created
January 12, 2012 02:55
-
-
Save mlbright/1598271 to your computer and use it in GitHub Desktop.
how to convert a png to grayscale in the go programming language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // see http://stackoverflow.com/questions/8697095/how-to-read-a-png-file-in-gray-scale-using-the-go-programming-language | |
| // Many thanks to Evan Shaw http://stackoverflow.com/users/510/evan-shaw | |
| 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) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment