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

How to Efficiently Extract a Pixel Array from a Golang Image Object?

DDD
DDDOriginal
2024-12-17 15:57:11980browse

How to Efficiently Extract a Pixel Array from a Golang Image Object?

Obtaining a Pixel Array from a Golang Image Object

To obtain a pixel array in the form of a byte array, the following approach can be employed.

Firstly, the image library provides the img.At(x, y).RGBA() method to retrieve the RGBA values for a specific pixel at coordinates (x, y) in the image. To obtain the 8-bit representation of these values, each component must be divided by 255.

To facilitate this process, a bi-dimensional array of pixels can be created as follows:

package main

import (
    "fmt"
    "image"
    "image/png"
    "os"
    "io"
    "net/http"
)

func main() {
    // Register the PNG format (can be extended to other formats)
    image.RegisterFormat("png", "png", png.Decode, png.DecodeConfig)

    file, err := os.Open("./image.png")

    if err != nil {
        fmt.Println("Error: File could not be opened")
        os.Exit(1)
    }

    defer file.Close()

    pixels, err := getPixels(file)

    if err != nil {
        fmt.Println("Error: Image could not be decoded")
        os.Exit(1)
    }

    fmt.Println(pixels)
}

func getPixels(file io.Reader) ([][]Pixel, error) {
    img, _, err := image.Decode(file)

    if err != nil {
        return nil, err
    }

    bounds := img.Bounds()
    width, height := bounds.Max.X, bounds.Max.Y

    var pixels [][]Pixel
    for y := 0; y < height; y++ {
        var row []Pixel
        for x := 0; x < width; x++ {
            row = append(row, rgbaToPixel(img.At(x, y).RGBA()))
        }
        pixels = append(pixels, row)
    }

    return pixels, nil
}

func rgbaToPixel(r uint32, g uint32, b uint32, a uint32) Pixel {
    return Pixel{int(r / 255), int(g / 255), int(b / 255), int(a / 255)}
}

type Pixel struct {
    R int
    G int
    B int
    A int
}

The above is the detailed content of How to Efficiently Extract a Pixel Array from a Golang Image Object?. 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