HowtoGo
Home / Standard Library / The image Package
Standard Library

The image Package

image defines the Image interface and the concrete pixel-buffer types (RGBA, NRGBA, Gray, Paletted) every Go image works with. image/png and image/jpeg add format-specific encoding and decoding; image/draw adds compositing one image onto another.

image.NewRGBA allocates a blank canvas from a Rectangle. Set writes one pixel; At reads one back, both through the same color.Color interface.

img := image.NewRGBA(image.Rect(0, 0, 4, 4))
img.Set(1, 1, color.RGBA{R: 255, A: 255})

fmt.Println(img.Bounds())
fmt.Println(img.At(1, 1))

Bounds reports the canvas as a half-open rectangle, (0,0)-(4,4) for 4x4 pixels. The pixel just set reads back as {255 0 0 255}: red, no green, no blue, fully opaque.

Terminal
(0,0)-(4,4)
{255 0 0 255}

Examples

NewRGBA allocates a blank canvas; Set writes one pixel at a time. png.Encode is lossless, so the same pixels come back byte-for-byte on decode.

img := image.NewRGBA(image.Rect(0, 0, 100, 100))
for y := 0; y < 100; y++ {
    for x := 0; x < 100; x++ {
        img.Set(x, y, color.RGBA{R: uint8(x * 2), G: uint8(y * 2), B: 120, A: 255})
    }
}

f, err := os.Create("gradient.png")
if err != nil {
    log.Fatal(err)
}
defer f.Close()

if err := png.Encode(f, img); err != nil {
    log.Fatal(err)
}
fmt.Println("wrote", "gradient.png")
Output
wrote gradient.png
A 320 by 200 Mandelbrot set, rendered pixel by pixel with image.NewRGBA and encoded as PNG

Output of the Mandelbrot set example above.

image package core

FunctionDescription
type Image interface{ ColorModel() color.Model; Bounds() Rectangle; At(x, y int) color.Color }
The interface every image type satisfies: a color model, a bounding rectangle, and per-pixel lookup.
type Point struct{ X, Y int }
A single coordinate.
Pt(X, Y int) Point
image.Pt(10, 20)
Shorthand for Point{X, Y}.
type Rectangle struct{ Min, Max Point }
A rectangle spanning [Min, Max), Max exclusive on both axes.
Rect(x0, y0, x1, y1 int) Rectangle
image.Rect(0, 0, 100, 60)
Shorthand for a Rectangle with Min{x0,y0} and Max{x1,y1}.
(Rectangle) Dx() int / Dy() int
The rectangle's width and height in pixels.
(Rectangle) In(r Rectangle) bool
Reports whether the rectangle is entirely within r.
NewRGBA(r Rectangle) *RGBA
image.NewRGBA(image.Rect(0, 0, 100, 60))
An in-memory, alpha-premultiplied 8-bit-per-channel canvas.
NewNRGBA(r Rectangle) *NRGBA
Like NewRGBA, but channels aren't alpha-premultiplied.
NewGray(r Rectangle) *Gray
An 8-bit grayscale canvas.
NewPaletted(r Rectangle, p color.Palette) *Paletted
A canvas backed by a fixed color palette; what GIF frames use.
(*RGBA) Set(x, y int, c color.Color)
img.Set(1, 1, color.RGBA{R: 255, A: 255})
Writes a pixel, converting c to the image's own color model.
type Uniform struct{ C color.Color }
An infinite image of one solid color, useful as a fill source for image/draw.
Decode(r io.Reader) (Image, string, error)
Decodes an image in any registered format, returning the format name.
DecodeConfig(r io.Reader) (Config, string, error)
Reads only the header: dimensions and color model, without decoding pixel data.
RegisterFormat(name, magic string, decode func(io.Reader) (Image, error), decodeConfig func(io.Reader) (Config, error))
Registers a format's decoder; called by each format package's own init, e.g. image/png's.
type Config struct{ ColorModel color.Model; Width, Height int }
An image's dimensions and color model without its pixel data.
ErrFormat error
Returned by Decode when no registered format recognizes the input.

image/color

FunctionDescription
type Color interface{ RGBA() (r, g, b, a uint32) }
The interface every color type satisfies; values are alpha-premultiplied and scaled to 16 bits.
type Model interface{ Convert(c Color) Color }
Converts an arbitrary Color into one image's own color representation.
type RGBA struct{ R, G, B, A uint8 }
8-bit color, alpha-premultiplied.
type NRGBA struct{ R, G, B, A uint8 }
8-bit color, not alpha-premultiplied; the type to reach for when specifying R/G/B independently of A.
type Gray struct{ Y uint8 }
8-bit grayscale.
type Alpha struct{ A uint8 }
8-bit alpha only, no color.
RGBAModel, NRGBAModel, GrayModel, AlphaModel Model
color.GrayModel.Convert(c)
Predefined Models matching each color type above.
type Palette []Color
An ordered set of colors, e.g. the fixed palette a GIF frame draws from.
(Palette) Index(c Color) int
Returns the palette entry closest to c.
(Palette) Convert(c Color) Color
Returns the closest palette entry itself, not just its index.

image/png

FunctionDescription
Encode(w io.Writer, m image.Image) error
Writes m to w as a PNG. Lossless; output size depends only on compression, not a quality setting.
Decode(r io.Reader) (image.Image, error)
Decodes a PNG.
DecodeConfig(r io.Reader) (image.Config, error)
Reads a PNG's dimensions and color model without decoding pixel data.
type Encoder struct{ CompressionLevel CompressionLevel }
Use Encoder.Encode instead of the package-level Encode to control compression.
DefaultCompression, NoCompression, BestSpeed, BestCompression CompressionLevel
The CompressionLevel values Encoder.CompressionLevel accepts.

image/jpeg

FunctionDescription
Encode(w io.Writer, m image.Image, o *Options) error
jpeg.Encode(w, img, &jpeg.Options{Quality: 80})
Writes m to w as a JPEG; a nil Options uses the default quality.
type Options struct{ Quality int }
Quality from 1 to 100; higher keeps more detail at a larger file size.
Decode(r io.Reader) (image.Image, error)
Decodes a JPEG. The concrete type is usually *image.YCbCr, JPEG's native color model.
DecodeConfig(r io.Reader) (image.Config, error)
Reads a JPEG's dimensions and color model without decoding pixel data.
type FormatError string
The error type Decode returns for malformed JPEG data.

image/draw

FunctionDescription
Draw(dst Image, r Rectangle, src image.Image, sp Point, op Op)
draw.Draw(dst, r, src, sp, draw.Over)
Copies src onto dst within r, aligning src's sp to r's top-left corner.
Src, Over Op
Src overwrites dst outright; Over alpha-blends src on top of dst's existing pixels.
type Image interface{ image.Image; Set(x, y int, c color.Color) }
The mutable subset of image.Image that Draw requires as a destination.
DrawMask(dst Image, r Rectangle, src image.Image, sp Point, mask image.Image, mp Point, op Op)
Like Draw, but mask's alpha channel scales src's contribution per pixel.
type Drawer interface{ Draw(dst Image, r Rectangle, src image.Image, sp Point) }
The interface FloydSteinberg and other ditherers implement.

Gotchas

  • image.Decode only recognizes formats registered by an imported package. Forgetting _ "image/jpeg" or _ "image/png" makes it fail with image: unknown format even on a well-formed file.
  • image.Image has no Set method, only At. Mutating pixels needs a concrete type like *image.RGBA, or the narrower draw.Image interface that adds Set back.
  • JPEG is lossy. Decoding a JPEG, editing it, and re-encoding it degrades quality further each round trip; PNG round-trips losslessly.
  • jpeg.Decode usually returns a *image.YCbCr, not *image.RGBA, since that's JPEG's native color model. Calling At still works through the Image interface either way.