How to Process Images in Go (image Package)

Load images with the image package and manipulate pixels using image/draw to create or modify graphics in Go.

Use the image package to decode image files and the image/draw package to manipulate pixels. The following example loads a PNG file, creates a new image, and draws a red rectangle on it.

package main

import (
	"image"
	"image/color"
	"image/draw"
	"image/png"
	"os"
)

func main() {
	f, _ := os.Open("input.png")
	orig, _, _ := png.Decode(f)
	f.Close()

	newImg := image.NewRGBA(orig.Bounds())
	rect := image.Rect(10, 10, 100, 100)
	c := color.RGBA{255, 0, 0, 255}
	draw.Draw(newImg, rect, image.NewUniform(c), image.Point{}, draw.Src)

	out, _ := os.Create("output.png")
	png.Encode(out, newImg)
	out.Close()
}