Skip to content

Instantly share code, notes, and snippets.

@ericho
Created February 17, 2020 15:21
Show Gist options
  • Save ericho/cc872097db5a9638b154e70b3f0bb359 to your computer and use it in GitHub Desktop.
Save ericho/cc872097db5a9638b154e70b3f0bb359 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"image"
"image/color"
// This is an implicit import to register jpeg decoding.
"image/png"
"os"
)
func getGray(c color.Color) color.Color {
R, G, B, A := c.RGBA()
n := (R >> 8) + (G >> 8) + (B >> 8)
gray := n / 3
return color.RGBA{
R: uint8(gray),
G: uint8(gray),
B: uint8(gray),
A: uint8(A),
}
}
func getGray2(c color.Color) color.Color {
R, G, B, A := c.RGBA()
r := float64((R >> 8)) * 1.5
g := float64((G >> 8)) * 0.8
b := float64((B >> 8)) * 0.3
gray := uint8((r + g + b) / 3)
return color.RGBA{
R: gray,
G: gray,
B: gray,
A: uint8(A),
}
}
func main() {
imgFile, err := os.Open("data/erich.png")
defer imgFile.Close()
if err != nil {
fmt.Println("Error opening the image.")
return
}
img, imgType, err := image.Decode(imgFile)
if err != nil {
fmt.Println("Error decoding image.", err)
return
}
fmt.Printf("Image in '%s' format\n", imgType)
fmt.Printf("Bounds are %+v\n", img.Bounds())
fmt.Printf("Image has size weigth = %d - height = %d\n",
img.Bounds().Max.X, img.Bounds().Max.Y)
img2 := image.NewRGBA(image.Rect(0, 0,
img.Bounds().Max.X, img.Bounds().Max.X))
for y := 0; y < img.Bounds().Max.Y; y++ {
for x := 0; x < img.Bounds().Max.X; x++ {
newColor := getGray2(img.At(x, y))
img2.Set(x, y, newColor)
}
}
out, err := os.Create("data/output2.png")
defer out.Close()
if err != nil {
fmt.Println("Error creating output image.")
return
}
err = png.Encode(out, img2)
if err != nil {
fmt.Println("Failed to encode image: ", err)
return
}
fmt.Println("Image saved!")
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment