An image.RGBA is a mutable raster image whose pixels use red, green, blue, and alpha components. It fits problems where exact pixel values encode geometry, categories, or numerical data. PNG is useful when altered pixel colors would damage the meaning of the image. section 9.1.1 section 9.7
Use the type through the image package’s coordinate and pixel operations:
- Call Bounds() to obtain the image’s Min and Max points; do not assume that (0, 0) is always the upper-left pixel. section 9.3.1 section 9.7
- Call RGBAAt(x, y) to retrieve a color.RGBA directly, avoiding repeated conversion from image.Image and color.Color. section 9.2.2 section 9.7
- Call Set(x, y, rgba) when writing a path or other annotation into the mutable image. section 9.7
- Scan rows outside columns because raster formats commonly store horizontally adjacent pixels next to one another in memory. section 9.3.1 section 9.7
Loading a maze PNG
Decode the file with image/png, assert the resulting image.Image to *image.RGBA, and return an error when the file cannot be opened, decoded, or represented as RGBA. A maze solver can then compare RGBAAt values with a palette to find its entrance and traverse exact wall, path, and treasure pixels. section 9.2.2 section 9.3.1
Listing 9.2 imagefile.go: Opening the maze image
package main
import (
"fmt"
"image"
"image/png"
"os"
)
// openMaze opens a RGBA png image from a path.
func openMaze(imagePath string) (*image.RGBA, error) { #1
f, err := os.Open(imagePath) #2
if err != nil {
return nil, fmt.Errorf("unable to open image %s: %w", imagePath, err)
}
defer f.Close()
img, err := png.Decode(f) #3
if err != nil {
return nil, fmt.Errorf("unable to load input image from %s: %w",
imagePath, err)
}
rgbaImage, ok := img.(*image.RGBA) #4
if !ok {
return nil, fmt.Errorf(
"expected RGBA image, got %T", img) #5
}
return rgbaImage, nil
}
The complete openMaze implementation shows file handling, deferred closing, PNG decoding, RGBA type assertion, and explicit errors. section 9.2.2
