Home >Backend Development >Golang >How to Extract a Pixel Array from a Go Image?

How to Extract a Pixel Array from a Go Image?

DDD
DDDOriginal
2024-12-06 18:07:17219browse

How to Extract a Pixel Array from a Go Image?

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:

  1. 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)
    }
  2. Create a bi-dimensional array to store the pixel values:

    var pixels [][]Pixel
  3. 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)
    }
  4. 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)}
    }
  5. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn