How to Get a Pixel Array from a Go Image
In Go, you can obtain a pixel array from an image loaded from a file using the image package. This array can be passed to the texImage2D method of the Contex from the /mobile/gl package.
To get a pixel array, follow these steps:
Load the image from a file:
a, err := asset.Open("key.jpeg") if err != nil { log.Fatal(err) } defer a.Close() img, _, err := image.Decode(a) if err != nil { log.Fatal(err) }
Create a bi-dimensional array to store the pixel values:
var pixels [][]Pixel
Iterate through the image pixels and extract their RGBA values:
bounds := img.Bounds() width, height := bounds.Max.X, bounds.Max.Y for y := 0; y < height; y++ { var row []Pixel for x := 0; x < width; x++ { r, g, b, a := img.At(x, y).RGBA() pixel := rgbaToPixel(r, g, b, a) row = append(row, pixel) } pixels = append(pixels, row) }
Convert the RGBA values to pixels:
func rgbaToPixel(r uint32, g uint32, b uint32, a uint32) Pixel { return Pixel{int(r / 257), int(g / 257), int(b / 257), int(a / 257)} }
Return the pixel array:
return pixels
The returned pixel array can be passed to the texImage2D method to display the image.
The above is the detailed content of How to Extract a Pixel Array from a Go Image?. For more information, please follow other related articles on the PHP Chinese website!