Golang : Get RGBA values of each image pixel
Problem :
You need to find out each pixels R,G,B,A values on an image. Maybe to do ASCII art, edge detection algorithm for cognitive purpose or some advanced image processing. How to do that?
Solution :
Get the width and height of an image file with image.DecodeConfig()
function and then iterate each pixel base on width/height on the image covering entire image. At each pixel, use image.At()
function's RGBA() method to retrieve the R,G,B,A values.
For example :
package main
import (
"fmt"
"image"
"image/jpeg"
"os"
)
func init() {
// damn important or else At(), Bounds() functions will
// caused memory pointer error!!
image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig)
}
func main() {
imgfile, err := os.Open("./img.jpg")
if err != nil {
fmt.Println("img.jpg file not found!")
os.Exit(1)
}
defer imgfile.Close()
// get image height and width with image/jpeg
// change accordinly if file is png or gif
imgCfg, _, err := image.DecodeConfig(imgfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
width := imgCfg.Width
height := imgCfg.Height
fmt.Println("Width : ", width)
fmt.Println("Height : ", height)
// we need to reset the io.Reader again for image.Decode() function below to work
// otherwise we will - panic: runtime error: invalid memory address or nil pointer dereference
// there is no build in rewind for io.Reader, use Seek(0,0)
imgfile.Seek(0, 0)
// get the image
img, _, err := image.Decode(imgfile)
fmt.Println(img.At(10, 10).RGBA())
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
r, g, b, a := img.At(x, y).RGBA()
fmt.Printf("[X : %d Y : %v] R : %v, G : %v, B : %v, A : %v \n", x, y, r, g, b, a)
}
}
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.5k Android Studio : Create custom icons for your application example
+11.9k Golang : Clean formatting/indenting or pretty print JSON result
+11.1k Google Maps URL parameters configuration
+6.2k Golang & Javascript : How to save cropped image to file on server
+25.3k Golang : Generate MD5 checksum of a file
+6.8k Swift : substringWithRange() function example
+6.1k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+9.7k Golang : interface - when and where to use examples
+16.2k Golang : Loop each day of the current month example
+7k Golang : Takes a plural word and makes it singular
+6k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+8.3k Your page has meta tags in the body instead of the head