Last active
September 7, 2022 07:28
-
-
Save shyamvlmna/4669d3f459cadd290b527fbd64b43ee3 to your computer and use it in GitHub Desktop.
A simple way of grayscaling an image using standard libraries in golang
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
package main | |
import ( | |
"fmt" | |
"image" | |
"image/color" | |
"image/png" | |
"os" | |
) | |
func main() { | |
// open and load the image file | |
imgfile, err := os.Open("image.png") | |
if err != nil { | |
fmt.Println(err) | |
} | |
defer imgfile.Close() | |
// decode the image file to image.Image type | |
img, _, err := image.Decode(imgfile) | |
if err != nil { | |
fmt.Println(err) | |
} | |
// target to store the grayscaled image, having the same dimensions as the image file | |
target := image.NewRGBA64(img.Bounds()) | |
// change the colour of each and every pixels of the image file and set to the target | |
i := 0 | |
for i < img.Bounds().Max.Y { | |
j := 0 | |
for j < img.Bounds().Max.X { | |
r, g, b, a := img.At(j, i).RGBA() | |
// set r,g & b values of the pixel to average of r,g,b to make it grayscale | |
average := (r + g + b) / 3 | |
target.Set(j, i, color.NRGBA64{R: uint16(average), G: uint16(average), B: uint16(average), A: uint16(a)}) | |
j++ | |
} | |
i++ | |
} | |
// create a new file for the grayscale image | |
res, err := os.Create("result.png") | |
if err != nil { | |
fmt.Println(err) | |
} | |
// encode the grayscaled image.Image to result file | |
if err := png.Encode(res, target); err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment