Skip to content

Instantly share code, notes, and snippets.

@suyash
Last active September 21, 2016 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suyash/bf518c4c405089ceda31e0288e8f5885 to your computer and use it in GitHub Desktop.
Save suyash/bf518c4c405089ceda31e0288e8f5885 to your computer and use it in GitHub Desktop.
grayscale converter
*.jpg
*.jpeg
*.png
*.gif
package main
import (
"flag"
"fmt"
"image"
"image/color"
"image/gif"
"image/jpeg"
"image/png"
"os"
)
func main() {
flag.Parse()
if flag.NArg() < 1 {
fmt.Println("need atleast one image")
return
}
file := flag.Arg(0)
f, err := os.Open(file)
if err != nil {
panic(err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
img, err = png.Decode(f)
if err != nil {
img, err = jpeg.Decode(f)
if err != nil {
img, err = gif.Decode(f)
if err != nil {
panic("decode my ass")
}
}
}
}
oimg := image.NewGray(img.Bounds())
for i := img.Bounds().Min.X; i < img.Bounds().Max.X; i++ {
for j := img.Bounds().Min.Y; j < img.Bounds().Max.Y; j++ {
c := img.At(i, j)
nc := color.GrayModel.Convert(c)
oimg.Set(i, j, nc)
}
}
o, err := os.Create("output.png")
if err != nil {
panic(err)
}
defer o.Close()
png.Encode(o, oimg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment