All formats

imaging

LanguageGo
LicenseMIT
Repositorygithub.com/disintegration/imaging
Documentationpkg.go.dev/github.com/disintegration/imaging
Depends ongolang.org/x/image (BMP and TIFF); PNG through the standard library
Read / writeyes / yes (uses image/png)

imaging adds the image operations missing from the Go standard library: resize with good filters (Lanczos, CatmullRom, Linear, Box, NearestNeighbor), fit and fill for thumbnails, crop, rotate, flip, blur, sharpen and color adjustments. It’s pure Go, has no cgo, and works with any image.Image.

imaging.Open and imaging.Save handle PNG, JPEG, GIF, TIFF and BMP, choosing the format from the file extension. PNG reading and writing goes through image/png, so the same limits apply: no text chunks and no APNG. Processing functions return *image.NRGBA. The package is stable and gets few updates.

Installation#

Shell
go get github.com/disintegration/imaging

Basic usage: open, resize and save a PNG#

Go
package main

import (
	"log"

	"github.com/disintegration/imaging"
)

func main() {
	img, err := imaging.Open("in.png")
	if err != nil {
		log.Fatal(err)
	}

	// width 800, height 0 keeps the aspect ratio
	resized := imaging.Resize(img, 800, 0, imaging.Lanczos)

	if err := imaging.Save(resized, "out.png"); err != nil {
		log.Fatal(err)
	}
}

How to make a square PNG thumbnail#

Fill resizes and crops to exactly the given size; Fit keeps the whole image inside the box:

Go
thumb := imaging.Fill(img, 200, 200, imaging.Center, imaging.Lanczos)
err := imaging.Save(thumb, "thumb.png")

fitted := imaging.Fit(img, 200, 200, imaging.Lanczos) // at most 200x200

How to set PNG compression level#

Go
import "image/png"

err := imaging.Save(img, "out.png", imaging.PNGCompressionLevel(png.BestCompression))

How to convert PNG to JPEG#

The format comes from the extension. Flatten transparency onto white first, because JPEG has no alpha:

Go
import (
	"image"
	"image/color"
)

src, err := imaging.Open("in.png")
if err != nil {
	log.Fatal(err)
}
bg := imaging.New(src.Bounds().Dx(), src.Bounds().Dy(), color.White)
flat := imaging.Overlay(bg, src, image.Pt(0, 0), 1.0)
err = imaging.Save(flat, "out.jpg", imaging.JPEGQuality(85))

How to crop, rotate and adjust a PNG#

Go
cropped := imaging.Crop(img, image.Rect(10, 10, 410, 310))
rotated := imaging.Rotate90(cropped)
brighter := imaging.AdjustBrightness(rotated, 10)  // -100 .. 100
gray := imaging.Grayscale(brighter)
err := imaging.Save(gray, "edited.png")

Tips#