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
Release: 2024-12-06 18:07:17
Original
175 people have browsed it

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

    var pixels [][]Pixel
    Copy after login
  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)
    }
    Copy after login
  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)}
    }
    Copy after login
  5. Return the pixel array:

    return pixels
    Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template