~/Golang Libraries for Graphics and Image Manipulation

Jan 17, 2020


Golang supports graphics and image manipulation using built-in and external packages. For most use cases, the standard image package is sufficient to decode, process, and encode JPEG, PNG, and GIF formats.

To draw shapes or images:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import (
  "image"
  "image/color"
  "image/draw"
  "image/png"
  "os"
)

func main() {
  img := image.NewRGBA(image.Rect(0, 0, 100, 100))
  draw.Draw(img, img.Bounds(), &image.Uniform{color.RGBA{255,0,0,255}}, image.Point{}, draw.Src)
  f, _ := os.Create("red.png")
  defer f.Close()
  png.Encode(f, img)
}

For advanced operations such as cropping, resizing or filtering, the github.com/disintegration/imaging library is popular. Resize an image example:

1
2
3
4
5
6
7
8
import (
  "github.com/disintegration/imaging"
  "image"
)

img, _ := imaging.Open("in.png")
resized := imaging.Resize(img, 200, 0, imaging.Lanczos)
imaging.Save(resized, "resized.png")

Other useful libraries:

Refer to the official tour or documentation for more examples.

Tags: [golang] [graphics] [images]