imaging package - github.com/disintegration/imaging - Go Packages (original) (raw)

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).

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)
}

}

This section is empty.

ErrUnsupportedFormat means the given image format is not supported.

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%.

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 gray image.

Examples:

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

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} } )

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)

AdjustSaturation changes the saturation of the image using the percentage parameter and returns the adjusted image. The percentage must be in the range (-100, 100). The percentage = 0 gives the original image. The percentage = 100 gives the image with the saturation value doubled for each pixel. The percentage = -100 gives the image with the saturation value zeroed for each pixel (grayscale).

Examples:

dstImage = imaging.AdjustSaturation(srcImage, 25) // Increase image saturation by 25%. dstImage = imaging.AdjustSaturation(srcImage, -10) // Decrease image saturation by 10%.

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.

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.

Example:

dstImage := imaging.Blur(srcImage, 3.5)

Clone returns a copy of the given image.

Convolve3x3 convolves the image with the specified 3x3 convolution kernel. Default parameters are used if a nil *ConvolveOptions is passed.

Convolve5x5 convolves the image with the specified 5x5 convolution kernel. Default parameters are used if a nil *ConvolveOptions is passed.

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. To achieve the correct aspect ratio without stretching, the source image will be cropped.

Example:

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

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

Example:

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

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.

Grayscale produces a grayscale version of the image.

Histogram returns a normalized histogram of an image.

Resulting histogram is represented as an array of 256 floats, where histogram[i] is a probability of a pixel being of a particular luminance i.

Invert produces an inverted (negated) version of the image.

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

Open loads an image from file.

Examples:

// Load an image from file. img, err := imaging.Open("test.jpg")

// Load an image and transform it depending on the EXIF orientation tag (if present). img, err := imaging.Open("test.jpg", imaging.AutoOrientation(true))

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.

Examples:

// Draw spriteImage over backgroundImage at the given position (x=50, y=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)

OverlayCenter overlays the img image to the center of the background image 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.

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.

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.

Example:

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

Rotate rotates an image by the given angle counter-clockwise . The angle parameter is the rotation angle in degrees. The bgColor parameter specifies the color of the uncovered zone after the rotation.

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. The format is determined from the filename extension: "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.

Examples:

// Save the image as PNG. err := imaging.Save(img, "out.png")

// Save the image as JPEG with optional quality parameter set to 80. err := imaging.Save(img, "out.jpg", imaging.JPEGQuality(80))

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

Example:

dstImage := imaging.Sharpen(srcImage, 3.5)

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.

Example:

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

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

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

Anchor is the anchor point for image alignment.

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

Anchor point positions.

type ConvolveOptions struct {

Normalize [bool](/builtin#bool)


Abs [bool](/builtin#bool)


Bias [int](/builtin#int)

}

ConvolveOptions are convolution parameters.

type DecodeOption func(*decodeConfig)

DecodeOption sets an optional parameter for the Decode and Open functions.

func AutoOrientation(enabled bool) DecodeOption

AutoOrientation returns a DecodeOption that sets the auto-orientation mode. If auto-orientation is enabled, the image will be transformed after decoding according to the EXIF orientation tag (if present). By default it's disabled.

type EncodeOption func(*encodeConfig)

EncodeOption sets an optional parameter for the Encode and Save functions.

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.

func GIFNumColors(numColors int) EncodeOption

GIFNumColors returns an EncodeOption that sets the maximum number of colors used in the GIF-encoded image. It ranges from 1 to 256. Default is 256.

GIFQuantizer returns an EncodeOption that sets the quantizer that is used to produce a palette of the GIF-encoded image.

func JPEGQuality(quality int) EncodeOption

JPEGQuality returns an EncodeOption that sets the output JPEG quality. Quality ranges from 1 to 100 inclusive, higher is better. Default is 95.

PNGCompressionLevel returns an EncodeOption that sets the compression level of the PNG-encoded image. Default is png.DefaultCompression.

Format is an image file format.

const ( JPEG Format = iota PNG GIF TIFF BMP )

Image file formats.

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.

ResampleFilter specifies a resampling filter to be used for image resizing.

General filter recommendations:

var BSpline ResampleFilter

BSpline is a smooth cubic filter (BC-spline; B=1; C=0).

var Bartlett ResampleFilter

Bartlett is a Bartlett-windowed sinc filter (3 lobes).

var Blackman ResampleFilter

Blackman is a Blackman-windowed sinc filter (3 lobes).

Box filter (averaging pixels).

var CatmullRom ResampleFilter

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

var Cosine ResampleFilter

Cosine is a Cosine-windowed sinc filter (3 lobes).

var Gaussian ResampleFilter

Gaussian is a Gaussian blurring filter.

var Hamming ResampleFilter

Hamming is a Hamming-windowed sinc filter (3 lobes).

Hann is a 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

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

var NearestNeighbor ResampleFilter

NearestNeighbor is a nearest-neighbor filter (no anti-aliasing).

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