Problem:
To create textures using the texImage2D method in the /mobile/gl package, access to pixel values is required. The task is to convert the pixel values of an image into a byte array, where RGBA values are arranged consecutively from left to right, top to bottom.
Solution:
Unfortunately, img.Pixels() is not a readily available method for extracting the raw pixel data. However, the solution lies in iterating over the pixels of the image and extracting their RGBA components. The following steps outline the approach:
Here's an example implementation that demonstrates the process:
package main import ( "fmt" "image" "image/png" "os" ) func main() { // Open the image file file, err := os.Open("./image.png") if err != nil { fmt.Println("Error: Unable to open the image file.") return } defer file.Close() // Decode the image img, _, err := image.Decode(file) if err != nil { fmt.Println("Error: Unable to decode the image.") return } // Get the pixel array pixelArray, err := GetPixelArray(img) if err != nil { fmt.Println("Error: Unable to get the pixel array.") return } fmt.Println("Pixel array:") fmt.Println(pixelArray) } // GetPixelArray converts an image to a byte array containing the RGBA values of its pixels. func GetPixelArray(img image.Image) ([]byte, error) { bounds := img.Bounds() width, height := bounds.Max.X, bounds.Max.Y // Create a byte array to store the pixel values pixelArray := make([]byte, 0, width*height*4) // Iterate over the pixels and add their RGBA values to the byte array for y := 0; y < height; y++ { for x := 0; x < width; x++ { r, g, b, a := img.At(x, y).RGBA() pixelArray = append(pixelArray, byte(r/257)) pixelArray = append(pixelArray, byte(g/257)) pixelArray = append(pixelArray, byte(b/257)) pixelArray = append(pixelArray, byte(a/257)) } } return pixelArray, nil }
This approach will provide you with a byte array containing the raw pixel data in the desired format for use with texImage2D.
The above is the detailed content of How to Convert Image Pixels to a Byte Array in Golang for OpenGL Texture Creation?. For more information, please follow other related articles on the PHP Chinese website!