Standard library patterns · 3 MIN READ

image.Image is three methods, not a file

Implement a solid-colour image the standard library will accept.

image.Image describes pixels through three methods: ColorModel, Bounds and At. A decoded PNG produces an image value; the encoded PNG file itself does not implement that interface. A type you write can implement the same pixel contract.

image/draw and image/png work with image interfaces rather than requiring one concrete bitmap type. This lesson supplies a solid rectangle with chosen bounds and color; encoding that image is a separate step.

SEE THE IDEA

Pixels and encoded files are separate representations

  1. 01

    Image contract

    go
    ColorModel, Bounds, At

    Describes pixels and their coordinates

  2. 02

    Concrete buffer

    go
    image.NewRGBA(bounds)

    Stores mutable pixels

  3. 03

    Encoding

    go
    png.Encode(writer, img)

    Turns pixels into PNG bytes

An image.Image is a pixel interface, not a filename or encoded data blob.

In practice

Read Bounds rather than assuming every image starts at (0,0). Image implementations may be views over shared pixel storage. Rendering and encoding are separate steps: the app can display a PNG written by a program, while the Go program still uses the standard image and encoding interfaces.

Watch out

A rectangle excludes Max. Iterate while x < bounds.Max.X and y < bounds.Max.Y.

Official reference ↗

Work through the exercise

go
package main

import (
	"image"
	"image/color"
)

type Solid struct {
	W, H int
	C    color.RGBA
}

func (s Solid) ColorModel() color.Model { return color.RGBAModel }
func (s Solid) Bounds() image.Rectangle { return image.Rectangle{} }
func (s Solid) At(x, y int) color.Color { return color.RGBA{} }

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.