Process images and color models
Process images and color models
An image.Image exposes Bounds, ColorModel and At. A rectangle has an inclusive minimum and exclusive maximum; its origin need not be zero. Colors may use different representations. NRGBA stores non-premultiplied components, while Color.RGBA returns 16-bit-range alpha-premultiplied values.
package main
import ( "fmt" "image" "image/color")
func main() { m := image.NewNRGBA(image.Rect(4, 5, 6, 6)) m.SetNRGBA(4, 5, color.NRGBA{R: 255, A: 128}) r, _, _, a := m.At(4, 5).RGBA() fmt.Println(m.Bounds().Dx(), m.Bounds().Dy(), r == a, a == 0x8080)}Iterate from Bounds().Min to Bounds().Max, excluding Max. The red component equals alpha here because the original red is maximal and other channels are zero. Do not interpret the uint32 results from RGBA as ordinary 8-bit channels; use a color model conversion when needed.
Expected output:
2 1 true trueCheck dimensions before decoding
package main
import ( "bytes" "fmt" "image" "image/color" "image/png")
func picture() []byte { m := image.NewNRGBA(image.Rect(0, 0, 2, 1)) m.SetNRGBA(1, 0, color.NRGBA{R: 255, A: 255}) var b bytes.Buffer if e := png.Encode(&b, m); e != nil { panic(e) } return b.Bytes()}func main() { b := picture() cfg, kind, e := image.DecodeConfig(bytes.NewReader(b)) if e != nil { panic(e) } if cfg.Width < 1 || cfg.Height < 1 || cfg.Width > 100 || cfg.Height > 100 { panic("dimensions") } m, _, e := image.Decode(bytes.NewReader(b)) if e != nil { panic(e) } fmt.Println(kind, cfg.Width, cfg.Height, m.Bounds().Dx())}Importing image/png registers PNG with image.Decode and DecodeConfig. For decoding only, a blank import can register a decoder. DecodeConfig consumes input, so use a new reader over the same bounded bytes. Limit input bytes and dimensions (and pixel count with overflow-safe arithmetic); configuration checks are not a complete hostile-input sandbox. JPEG is typically lossy; PNG is lossless.
Expected output:
png 2 1 2Try it locally
Decode the generated picture and compare the two pixels after converting to NRGBA. Print whether the left is transparent and the right is opaque red.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Specialized library 02: Process images and color models
Check the lesson objective before moving on.
What does Bounds().Max mean?
Why use a fresh reader after DecodeConfig?