imaging

package
Version: v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 14, 2015 License: MIT, AGPL-3.0, Apache-2.0 Imports: 16 Imported by: 0

README

Imaging

Package imaging provides basic image manipulation functions (resize, rotate, flip, crop, etc.). This package is based on the standard Go image package and works best along with it.

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

Installation

Imaging requires Go version 1.2 or greater.

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:

  • NearestNeighbor - Fastest resampling filter, no antialiasing.
  • Box - Simple and fast averaging filter appropriate for downscaling. When upscaling it's similar to NearestNeighbor.
  • Linear - Bilinear filter, smooth and reasonably fast.
  • MitchellNetravali - А smooth bicubic filter.
  • CatmullRom - A sharp bicubic filter.
  • Gaussian - Blurring filter that uses gaussian function, useful for noise removal.
  • Lanczos - High-quality resampling filter for photographic images yielding sharp results, but it's slower than cubic filters.

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. Will be resized from 512x512px to 128x128px.

srcImage

Filter Resize result
imaging.NearestNeighbor dstImage
imaging.Box dstImage
imaging.Linear dstImage
imaging.MitchellNetravali dstImage
imaging.CatmullRom dstImage
imaging.Gaussian dstImage
imaging.Lanczos dstImage

Resize functions comparison

Original image:

srcImage

Resize the image to width=100px and height=100px:

dstImage := imaging.Resize(srcImage, 100, 100, imaging.Lanczos)

dstImage

Resize the image to width=100px preserving the aspect ratio:

dstImage := imaging.Resize(srcImage, 100, 0, imaging.Lanczos)

dstImage

Resize the image to fit the 100x100px boundng box preserving the aspect ratio:

dstImage := imaging.Fit(srcImage, 100, 100, imaging.Lanczos)

dstImage

Resize and crop the image with a center anchor point to fill the 100x100px area:

dstImage := imaging.Fill(srcImage, 100, 100, imaging.Center, imaging.Lanczos)

dstImage

Gaussian Blur
dstImage := imaging.Blur(srcImage, 0.5)

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

Original image Sigma = 0.5 Sigma = 1.5
srcImage dstImage dstImage
Sharpening
dstImage := imaging.Sharpen(srcImage, 0.5)

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

Original image Sigma = 0.5 Sigma = 1.5
srcImage dstImage dstImage
Gamma correction
dstImage := imaging.AdjustGamma(srcImage, 0.75)
Original image Gamma = 0.75 Gamma = 1.25
srcImage dstImage dstImage
Contrast adjustment
dstImage := imaging.AdjustContrast(srcImage, 20)
Original image Contrast = 20 Contrast = -20
srcImage dstImage dstImage
Brightness adjustment
dstImage := imaging.AdjustBrightness(srcImage, 20)
Original image Brightness = 20 Brightness = -20
srcImage dstImage dstImage
Complete code example

Here is the code example that loads several images, makes thumbnails of them and combines them together side-by-side.

package main

import (
    "image"
    "image/color"
    
    "github.com/disintegration/imaging"
)

func main() {

    // input files
    files := []string{"01.jpg", "02.jpg", "03.jpg"}

    // load images and make 100x100 thumbnails of them
    var thumbnails []image.Image
    for _, file := range files {
        img, err := imaging.Open(file)
        if err != nil {
            panic(err)
        }
        thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom)
        thumbnails = append(thumbnails, thumb)
    }

    // create a new blank image
    dst := imaging.New(100*len(thumbnails), 100, color.NRGBA{0, 0, 0, 0})

    // paste thumbnails into the new image side by side
    for i, thumb := range thumbnails {
        dst = imaging.Paste(dst, thumb, image.Pt(i*100, 0))
    }

    // save the combined image to file
    err := imaging.Save(dst, "dst.jpg")
    if err != nil {
        panic(err)
    }
}

Documentation

Overview

Package imaging provides basic image manipulation functions (resize, rotate, flip, crop, etc.). This package is based on the standard Go image package and works best along with it.

Image manipulation functions provided by the package take any image type that implements `image.Image` interface as an input, and return a new image of `*image.NRGBA` type (32bit RGBA colors, not premultiplied by alpha).

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnsupportedFormat = errors.New("imaging: unsupported image format")
)

Functions

func AdjustBrightness

func AdjustBrightness(img image.Image, percentage float64) *image.NRGBA

AdjustBrightness changes the brightness of the image using the percentage parameter and returns the adjusted image. The percentage must be in range (-100, 100). The percentage = 0 gives the original image. The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.

Examples:

dstImage = imaging.AdjustBrightness(srcImage, -15) // decrease image brightness by 15%
dstImage = imaging.AdjustBrightness(srcImage, 10) // increase image brightness by 10%

func AdjustContrast

func AdjustContrast(img image.Image, percentage float64) *image.NRGBA

AdjustContrast changes the contrast of the image using the percentage parameter and returns the adjusted image. The percentage must be in range (-100, 100). The percentage = 0 gives the original image. The percentage = -100 gives solid grey image.

Examples:

dstImage = imaging.AdjustContrast(srcImage, -10) // decrease image contrast by 10%
dstImage = imaging.AdjustContrast(srcImage, 20) // increase image contrast by 20%

func AdjustFunc

func AdjustFunc(img image.Image, fn func(c color.NRGBA) color.NRGBA) *image.NRGBA

AdjustFunc applies the fn function to each pixel of the img image and returns the adjusted image.

Example:

dstImage = imaging.AdjustFunc(
	srcImage,
	func(c color.NRGBA) color.NRGBA {
		// shift the red channel by 16
		r := int(c.R) + 16
		if r > 255 {
			r = 255
		}
		return color.NRGBA{uint8(r), c.G, c.B, c.A}
	}
)

func AdjustGamma

func AdjustGamma(img image.Image, gamma float64) *image.NRGBA

AdjustGamma performs a gamma correction on the image and returns the adjusted image. Gamma parameter must be positive. Gamma = 1.0 gives the original image. Gamma less than 1.0 darkens the image and gamma greater than 1.0 lightens it.

Example:

dstImage = imaging.AdjustGamma(srcImage, 0.7)

func AdjustSigmoid

func AdjustSigmoid(img image.Image, midpoint, factor float64) *image.NRGBA

AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. The midpoint parameter is the midpoint of contrast that must be between 0 and 1, typically 0.5. The factor parameter indicates how much to increase or decrease the contrast, typically in range (-10, 10). If the factor parameter is positive the image contrast is increased otherwise the contrast is decreased.

Examples:

dstImage = imaging.AdjustSigmoid(srcImage, 0.5, 3.0) // increase the contrast
dstImage = imaging.AdjustSigmoid(srcImage, 0.5, -3.0) // decrease the contrast

func Blur

func Blur(img image.Image, sigma float64) *image.NRGBA

Blur produces a blurred version of the image using a Gaussian function. Sigma parameter must be positive and indicates how much the image will be blurred.

Usage example:

dstImage := imaging.Blur(srcImage, 3.5)

func Clone

func Clone(img image.Image) *image.NRGBA

Clone returns a copy of the given image.

func Crop

func Crop(img image.Image, rect image.Rectangle) *image.NRGBA

Crop cuts out a rectangular region with the specified bounds from the image and returns the cropped image.

func CropAnchor

func CropAnchor(img image.Image, width, height int, anchor Anchor) *image.NRGBA

CropAnchor cuts out a rectangular region with the specified size from the image using the specified anchor point and returns the cropped image.

func CropCenter

func CropCenter(img image.Image, width, height int) *image.NRGBA

CropCenter cuts out a rectangular region with the specified size from the center of the image and returns the cropped image.

func Decode

func Decode(r io.Reader) (image.Image, error)

Decode reads an image from r.

func Encode

func Encode(w io.Writer, img image.Image, format Format) error

Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).

func Fill added in v1.3.0

func Fill(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA

Fill scales the image to the smallest possible size that will cover the specified dimensions, crops the resized image to the specified dimensions using the given anchor point and returns the transformed image.

Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.

Usage example:

dstImage := imaging.Fill(srcImage, 800, 600, imaging.Center, imaging.Lanczos)

func Fit

func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA

Fit scales down the image using the specified resample filter to fit the specified maximum width and height and returns the transformed image.

Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.

Usage example:

dstImage := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)

func FlipH

func FlipH(img image.Image) *image.NRGBA

FlipH flips the image horizontally (from left to right) and returns the transformed image.

func FlipV

func FlipV(img image.Image) *image.NRGBA

FlipV flips the image vertically (from top to bottom) and returns the transformed image.

func Grayscale

func Grayscale(img image.Image) *image.NRGBA

Grayscale produces grayscale version of the image.

func Invert

func Invert(img image.Image) *image.NRGBA

Invert produces inverted (negated) version of the image.

func New

func New(width, height int, fillColor color.Color) *image.NRGBA

New creates a new image with the specified width and height, and fills it with the specified color.

func Open

func Open(filename string) (image.Image, error)

Open loads an image from file

func Overlay

func Overlay(background, img image.Image, pos image.Point, opacity float64) *image.NRGBA

Overlay draws the img image over the background image at given position and returns the combined image. Opacity parameter is the opacity of the img image layer, used to compose the images, it must be from 0.0 to 1.0.

Usage examples:

// draw the sprite over the background at position (50, 50)
dstImage := imaging.Overlay(backgroundImage, spriteImage, image.Pt(50, 50), 1.0)

// blend two opaque images of the same size
dstImage := imaging.Overlay(imageOne, imageTwo, image.Pt(0, 0), 0.5)

func Paste

func Paste(background, img image.Image, pos image.Point) *image.NRGBA

Paste pastes the img image to the background image at the specified position and returns the combined image.

func PasteCenter

func PasteCenter(background, img image.Image) *image.NRGBA

PasteCenter pastes the img image to the center of the background image and returns the combined image.

func Resize

func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA

Resize resizes the image to the specified width and height using the specified resampling filter and returns the transformed image. If one of width or height is 0, the image aspect ratio is preserved.

Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.

Usage example:

dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)

func Rotate180

func Rotate180(img image.Image) *image.NRGBA

Rotate180 rotates the image 180 degrees counterclockwise and returns the transformed image.

func Rotate270

func Rotate270(img image.Image) *image.NRGBA

Rotate270 rotates the image 270 degrees counterclockwise and returns the transformed image.

func Rotate90

func Rotate90(img image.Image) *image.NRGBA

Rotate90 rotates the image 90 degrees counterclockwise and returns the transformed image.

func Save

func Save(img image.Image, filename string) (err error)

Save saves the image to file with the specified filename. The format is determined from the filename extension: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.

func Sharpen

func Sharpen(img image.Image, sigma float64) *image.NRGBA

Sharpen produces a sharpened version of the image. Sigma parameter must be positive and indicates how much the image will be sharpened.

Usage example:

dstImage := imaging.Sharpen(srcImage, 3.5)

func Thumbnail

func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA

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.

Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.

Usage example:

dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)

func Transpose

func Transpose(img image.Image) *image.NRGBA

Transpose flips the image horizontally and rotates 90 degrees counter-clockwise.

func Transverse

func Transverse(img image.Image) *image.NRGBA

Transverse flips the image vertically and rotates 90 degrees counter-clockwise.

Types

type Anchor

type Anchor int

Anchor is the anchor point for image alignment.

const (
	Center Anchor = iota
	TopLeft
	Top
	TopRight
	Left
	Right
	BottomLeft
	Bottom
	BottomRight
)

type Format

type Format int
const (
	JPEG Format = iota
	PNG
	GIF
	TIFF
	BMP
)

func (Format) String

func (f Format) String() string

type ResampleFilter

type ResampleFilter struct {
	Support float64
	Kernel  func(float64) float64
}

Resample filter struct. It can be used to make custom filters.

Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali, CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.

General filter recommendations:

- Lanczos
	Probably the best resampling filter for photographic images yielding sharp results,
	but it's slower than cubic filters (see below).

- CatmullRom
	A sharp cubic filter. It's a good filter for both upscaling and downscaling if sharp results are needed.

- MitchellNetravali
	A high quality cubic filter that produces smoother results with less ringing than CatmullRom.

- BSpline
	A good filter if a very smooth output is needed.

- Linear
	Bilinear interpolation filter, produces reasonably good, smooth output. It's faster than cubic filters.

- Box
	Simple and fast resampling filter appropriate for downscaling.
	When upscaling it's similar to NearestNeighbor.

- NearestNeighbor
	Fastest resample filter, no antialiasing at all. Rarely used.
var BSpline ResampleFilter

Cubic B-spline - smooth cubic filter (BC-spline; B=1; C=0).

var Bartlett ResampleFilter

Bartlett-windowed sinc filter (3 lobes).

var Blackman ResampleFilter

Blackman-windowed sinc filter (3 lobes).

var Box ResampleFilter

Box filter (averaging pixels).

var CatmullRom ResampleFilter

Catmull-Rom - sharp cubic filter (BC-spline; B=0; C=0.5).

var Cosine ResampleFilter

Cosine-windowed sinc filter (3 lobes).

var Gaussian ResampleFilter

Gaussian Blurring Filter.

var Hamming ResampleFilter

Hamming-windowed sinc filter (3 lobes).

var Hann ResampleFilter

Hann-windowed sinc filter (3 lobes).

var Hermite ResampleFilter

Hermite cubic spline filter (BC-spline; B=0; C=0).

var Lanczos ResampleFilter

Lanczos filter (3 lobes).

var Linear ResampleFilter

Linear filter.

var MitchellNetravali ResampleFilter

Mitchell-Netravali cubic filter (BC-spline; B=1/3; C=1/3).

var NearestNeighbor ResampleFilter

Nearest-neighbor filter, no anti-aliasing.

var Welch ResampleFilter

Welch-windowed sinc filter (parabolic window, 3 lobes).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL