Categorygithub.com/disintegration/imaging
modulepackage
1.6.2
Repository: https://github.com/disintegration/imaging.git
Documentation: pkg.go.dev

# README

Imaging

GoDoc Build Status Coverage Status Go Report Card

Package imaging provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.).

All the image processing functions provided by the package accept any image type that implements image.Image interface as an input, and return a new image of *image.NRGBA type (32bit RGBA colors, non-premultiplied alpha).

Installation

go get -u github.com/disintegration/imaging

Documentation

http://godoc.org/github.com/disintegration/imaging

Usage examples

A few usage examples can be found below. See the documentation for the full list of supported functions.

Image resizing

// Resize srcImage to size = 128x128px using the Lanczos filter.
dstImage128 := imaging.Resize(srcImage, 128, 128, imaging.Lanczos)

// Resize srcImage to width = 800px preserving the aspect ratio.
dstImage800 := imaging.Resize(srcImage, 800, 0, imaging.Lanczos)

// Scale down srcImage to fit the 800x600px bounding box.
dstImageFit := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)

// Resize and crop the srcImage to fill the 100x100px area.
dstImageFill := imaging.Fill(srcImage, 100, 100, imaging.Center, imaging.Lanczos)

Imaging supports image resizing using various resampling filters. The most notable ones:

  • Lanczos - A high-quality resampling filter for photographic images yielding sharp results.
  • CatmullRom - A sharp cubic filter that is faster than Lanczos filter while providing similar results.
  • MitchellNetravali - A cubic filter that produces smoother results with less ringing artifacts than CatmullRom.
  • Linear - Bilinear resampling filter, produces smooth output. Faster than cubic filters.
  • Box - Simple and fast averaging filter appropriate for downscaling. When upscaling it's similar to NearestNeighbor.
  • NearestNeighbor - Fastest resampling filter, no antialiasing.

The full list of supported filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine. Custom filters can be created using ResampleFilter struct.

Resampling filters comparison

Original image:

srcImage

The same image resized from 600x400px to 150x100px using different resampling filters. From faster (lower quality) to slower (higher quality):

FilterResize result
imaging.NearestNeighbordstImage
imaging.LineardstImage
imaging.CatmullRomdstImage
imaging.LanczosdstImage

Gaussian Blur

dstImage := imaging.Blur(srcImage, 0.5)

Sigma parameter allows to control the strength of the blurring effect.

Original imageSigma = 0.5Sigma = 1.5
srcImagedstImagedstImage

Sharpening

dstImage := imaging.Sharpen(srcImage, 0.5)

Sharpen uses gaussian function internally. Sigma parameter allows to control the strength of the sharpening effect.

Original imageSigma = 0.5Sigma = 1.5
srcImagedstImagedstImage

Gamma correction

dstImage := imaging.AdjustGamma(srcImage, 0.75)
Original imageGamma = 0.75Gamma = 1.25
srcImagedstImagedstImage

Contrast adjustment

dstImage := imaging.AdjustContrast(srcImage, 20)
Original imageContrast = 15Contrast = -15
srcImagedstImagedstImage

Brightness adjustment

dstImage := imaging.AdjustBrightness(srcImage, 20)
Original imageBrightness = 10Brightness = -10
srcImagedstImagedstImage

Saturation adjustment

dstImage := imaging.AdjustSaturation(srcImage, 20)
Original imageSaturation = 30Saturation = -30
srcImagedstImagedstImage

FAQ

Incorrect image orientation after processing (e.g. an image appears rotated after resizing)

Most probably, the given image contains the EXIF orientation tag. The stadard image/* packages do not support loading and saving this kind of information. To fix the issue, try opening images with the AutoOrientation decode option. If this option is set to true, the image orientation is changed after decoding, according to the orientation tag (if present). Here's the example:

img, err := imaging.Open("test.jpg", imaging.AutoOrientation(true))

What's the difference between imaging and gift packages?

imaging is designed to be a lightweight and simple image manipulation package. It provides basic image processing functions and a few helper functions such as Open and Save. It consistently returns *image.NRGBA image type (8 bits per channel, RGBA).

gift supports more advanced image processing, for example, sRGB/Linear color space conversions. It also supports different output image types (e.g. 16 bits per channel) and provides easy-to-use API for chaining multiple processing steps together.

Example code

package main

import (
	"image"
	"image/color"
	"log"

	"github.com/disintegration/imaging"
)

func main() {
	// Open a test image.
	src, err := imaging.Open("testdata/flowers.png")
	if err != nil {
		log.Fatalf("failed to open image: %v", err)
	}

	// Crop the original image to 300x300px size using the center anchor.
	src = imaging.CropAnchor(src, 300, 300, imaging.Center)

	// Resize the cropped image to width = 200px preserving the aspect ratio.
	src = imaging.Resize(src, 200, 0, imaging.Lanczos)

	// Create a blurred version of the image.
	img1 := imaging.Blur(src, 5)

	// Create a grayscale version of the image with higher contrast and sharpness.
	img2 := imaging.Grayscale(src)
	img2 = imaging.AdjustContrast(img2, 20)
	img2 = imaging.Sharpen(img2, 2)

	// Create an inverted version of the image.
	img3 := imaging.Invert(src)

	// Create an embossed version of the image using a convolution filter.
	img4 := imaging.Convolve3x3(
		src,
		[9]float64{
			-1, -1, 0,
			-1, 1, 1,
			0, 1, 1,
		},
		nil,
	)

	// Create a new image and paste the four produced images into it.
	dst := imaging.New(400, 400, color.NRGBA{0, 0, 0, 0})
	dst = imaging.Paste(dst, img1, image.Pt(0, 0))
	dst = imaging.Paste(dst, img2, image.Pt(0, 200))
	dst = imaging.Paste(dst, img3, image.Pt(200, 0))
	dst = imaging.Paste(dst, img4, image.Pt(200, 200))

	// Save the resulting image as JPEG.
	err = imaging.Save(dst, "testdata/out_example.jpg")
	if err != nil {
		log.Fatalf("failed to save image: %v", err)
	}
}

Output:

dstImage

# Functions

AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image.
AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image.
AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.
AdjustGamma performs a gamma correction on the image and returns the adjusted image.
AdjustSaturation changes the saturation of the image using the percentage parameter and returns the adjusted image.
AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image.
AutoOrientation returns a DecodeOption that sets the auto-orientation mode.
Blur produces a blurred version of the image using a Gaussian function.
Clone returns a copy of the given image.
Convolve3x3 convolves the image with the specified 3x3 convolution kernel.
Convolve5x5 convolves the image with the specified 5x5 convolution kernel.
Crop cuts out a rectangular region with the specified bounds from the image and returns the cropped image.
CropAnchor cuts out a rectangular region with the specified size from the image using the specified anchor point and returns the cropped image.
CropCenter cuts out a rectangular region with the specified size from the center of the image and returns the cropped image.
Decode reads an image from r.
Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
Fill creates an image with the specified dimensions and fills it with the scaled source image.
Fit scales down the image using the specified resample filter to fit the specified maximum width and height and returns the transformed image.
FlipH flips the image horizontally (from left to right) and returns the transformed image.
FlipV flips the image vertically (from top to bottom) and returns the transformed image.
FormatFromExtension parses image format from filename extension: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
FormatFromFilename parses image format from filename: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
GIFDrawer returns an EncodeOption that sets the drawer that is used to convert the source image to the desired palette of the GIF-encoded image.
GIFNumColors returns an EncodeOption that sets the maximum number of colors used in the GIF-encoded image.
GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce a palette of the GIF-encoded image.
Grayscale produces a grayscale version of the image.
Histogram returns a normalized histogram of an image.
Invert produces an inverted (negated) version of the image.
JPEGQuality returns an EncodeOption that sets the output JPEG quality.
New creates a new image with the specified width and height, and fills it with the specified color.
Open loads an image from file.
Overlay draws the img image over the background image at given position and returns the combined image.
OverlayCenter overlays the img image to the center of the background image and returns the combined image.
Paste pastes the img image to the background image at the specified position and returns the combined image.
PasteCenter pastes the img image to the center of the background image and returns the combined image.
PNGCompressionLevel returns an EncodeOption that sets the compression level of the PNG-encoded image.
Resize resizes the image to the specified width and height using the specified resampling filter and returns the transformed image.
Rotate rotates an image by the given angle counter-clockwise .
Rotate180 rotates the image 180 degrees counter-clockwise and returns the transformed image.
Rotate270 rotates the image 270 degrees counter-clockwise and returns the transformed image.
Rotate90 rotates the image 90 degrees counter-clockwise and returns the transformed image.
Save saves the image to file with the specified filename.
Sharpen produces a sharpened version of the image.
Thumbnail scales the image up or down using the specified resample filter, crops it to the specified width and hight and returns the transformed image.
Transpose flips the image horizontally and rotates 90 degrees counter-clockwise.
Transverse flips the image vertically and rotates 90 degrees counter-clockwise.

# Constants

Image file formats.
Anchor point positions.
Anchor point positions.
Anchor point positions.
Anchor point positions.
Image file formats.
Image file formats.
Anchor point positions.
Image file formats.
Anchor point positions.
Image file formats.
Anchor point positions.
Anchor point positions.
Anchor point positions.

# Variables

Bartlett is a Bartlett-windowed sinc filter (3 lobes).
Blackman is a Blackman-windowed sinc filter (3 lobes).
Box filter (averaging pixels).
BSpline is a smooth cubic filter (BC-spline; B=1; C=0).
CatmullRom is a Catmull-Rom - sharp cubic filter (BC-spline; B=0; C=0.5).
Cosine is a Cosine-windowed sinc filter (3 lobes).
ErrUnsupportedFormat means the given image format is not supported.
Gaussian is a Gaussian blurring filter.
Hamming is a Hamming-windowed sinc filter (3 lobes).
Hann is a Hann-windowed sinc filter (3 lobes).
Hermite cubic spline filter (BC-spline; B=0; C=0).
Lanczos filter (3 lobes).
Linear filter.
MitchellNetravali is Mitchell-Netravali cubic filter (BC-spline; B=1/3; C=1/3).
NearestNeighbor is a nearest-neighbor filter (no anti-aliasing).
Welch is a Welch-windowed sinc filter (parabolic window, 3 lobes).

# Structs

ConvolveOptions are convolution parameters.
ResampleFilter specifies a resampling filter to be used for image resizing.

# Type aliases

Anchor is the anchor point for image alignment.
DecodeOption sets an optional parameter for the Decode and Open functions.
EncodeOption sets an optional parameter for the Encode and Save functions.
Format is an image file format.