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
- 01
Image contract
goColorModel, Bounds, AtDescribes pixels and their coordinates
- 02
Concrete buffer
goimage.NewRGBA(bounds)Stores mutable pixels
- 03
Encoding
gopng.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.
Work through the exercise
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() {}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.