Go Image Filtering Toolkit

Overview

GO IMAGE FILTERING TOOLKIT (GIFT)

GoDoc Build Status Coverage Status Go Report Card

Package gift provides a set of useful image processing filters.

Pure Go. No external dependencies outside of the Go standard library.

INSTALLATION / UPDATING

go get -u github.com/disintegration/gift

DOCUMENTATION

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

QUICK START

// 1. Create a new filter list and add some filters.
g := gift.New(
	gift.Resize(800, 0, gift.LanczosResampling),
	gift.UnsharpMask(1, 1, 0),
)

// 2. Create a new image of the corresponding size.
// dst is a new target image, src is the original image.
dst := image.NewRGBA(g.Bounds(src.Bounds()))

// 3. Use the Draw func to apply the filters to src and store the result in dst.
g.Draw(dst, src)

USAGE

To create a sequence of filters, the New function is used:

g := gift.New(
	gift.Grayscale(),
	gift.Contrast(10),
)

Filters also can be added using the Add method:

g.Add(GaussianBlur(2))

The Bounds method takes the bounds of the source image and returns appropriate bounds for the destination image to fit the result (for example, after using Resize or Rotate filters).

dst := image.NewRGBA(g.Bounds(src.Bounds()))

There are two methods available to apply these filters to an image:

  • Draw applies all the added filters to the src image and outputs the result to the dst image starting from the top-left corner (Min point).
g.Draw(dst, src)
  • DrawAt provides more control. It outputs the filtered src image to the dst image at the specified position using the specified image composition operator. This example is equivalent to the previous:
g.DrawAt(dst, src, dst.Bounds().Min, gift.CopyOperator)

Two image composition operators are supported by now:

  • CopyOperator - Replaces pixels of the dst image with pixels of the filtered src image. This mode is used by the Draw method.
  • OverOperator - Places the filtered src image on top of the dst image. This mode makes sence if the filtered src image has transparent areas.

Empty filter list can be used to create a copy of an image or to paste one image to another. For example:

// Create a new image with dimensions of the bgImage.
dstImage := image.NewRGBA(bgImage.Bounds())
// Copy the bgImage to the dstImage.
gift.New().Draw(dstImage, bgImage)
// Draw the fgImage over the dstImage at the (100, 100) position.
gift.New().DrawAt(dstImage, fgImage, image.Pt(100, 100), gift.OverOperator)

SUPPORTED FILTERS

  • Transformations

    • Crop(rect image.Rectangle)
    • CropToSize(width, height int, anchor Anchor)
    • FlipHorizontal()
    • FlipVertical()
    • Resize(width, height int, resampling Resampling)
    • ResizeToFill(width, height int, resampling Resampling, anchor Anchor)
    • ResizeToFit(width, height int, resampling Resampling)
    • Rotate(angle float32, backgroundColor color.Color, interpolation Interpolation)
    • Rotate180()
    • Rotate270()
    • Rotate90()
    • Transpose()
    • Transverse()
  • Adjustments & effects

    • Brightness(percentage float32)
    • ColorBalance(percentageRed, percentageGreen, percentageBlue float32)
    • ColorFunc(fn func(r0, g0, b0, a0 float32) (r, g, b, a float32))
    • Colorize(hue, saturation, percentage float32)
    • ColorspaceLinearToSRGB()
    • ColorspaceSRGBToLinear()
    • Contrast(percentage float32)
    • Convolution(kernel []float32, normalize, alpha, abs bool, delta float32)
    • Gamma(gamma float32)
    • GaussianBlur(sigma float32)
    • Grayscale()
    • Hue(shift float32)
    • Invert()
    • Maximum(ksize int, disk bool)
    • Mean(ksize int, disk bool)
    • Median(ksize int, disk bool)
    • Minimum(ksize int, disk bool)
    • Pixelate(size int)
    • Saturation(percentage float32)
    • Sepia(percentage float32)
    • Sigmoid(midpoint, factor float32)
    • Sobel()
    • Threshold(percentage float32)
    • UnsharpMask(sigma, amount, threshold float32)

FILTER EXAMPLES

The original image:

Resulting images after applying some of the filters:

name / result name / result name / result name / result
resize crop_to_size rotate_180 rotate_30
brightness_increase brightness_decrease contrast_increase contrast_decrease
saturation_increase saturation_decrease gamma_1.5 gamma_0.5
gaussian_blur unsharp_mask sigmoid pixelate
colorize grayscale sepia invert
mean median minimum maximum
hue_rotate color_balance color_func convolution_emboss

Here's the code that produces the above images:

package main

import (
	"image"
	"image/color"
	"image/png"
	"log"
	"os"

	"github.com/disintegration/gift"
)

func main() {
	src := loadImage("testdata/src.png")

	filters := map[string]gift.Filter{
		"resize":               gift.Resize(100, 0, gift.LanczosResampling),
		"crop_to_size":         gift.CropToSize(100, 100, gift.LeftAnchor),
		"rotate_180":           gift.Rotate180(),
		"rotate_30":            gift.Rotate(30, color.Transparent, gift.CubicInterpolation),
		"brightness_increase":  gift.Brightness(30),
		"brightness_decrease":  gift.Brightness(-30),
		"contrast_increase":    gift.Contrast(30),
		"contrast_decrease":    gift.Contrast(-30),
		"saturation_increase":  gift.Saturation(50),
		"saturation_decrease":  gift.Saturation(-50),
		"gamma_1.5":            gift.Gamma(1.5),
		"gamma_0.5":            gift.Gamma(0.5),
		"gaussian_blur":        gift.GaussianBlur(1),
		"unsharp_mask":         gift.UnsharpMask(1, 1, 0),
		"sigmoid":              gift.Sigmoid(0.5, 7),
		"pixelate":             gift.Pixelate(5),
		"colorize":             gift.Colorize(240, 50, 100),
		"grayscale":            gift.Grayscale(),
		"sepia":                gift.Sepia(100),
		"invert":               gift.Invert(),
		"mean":                 gift.Mean(5, true),
		"median":               gift.Median(5, true),
		"minimum":              gift.Minimum(5, true),
		"maximum":              gift.Maximum(5, true),
		"hue_rotate":           gift.Hue(45),
		"color_balance":        gift.ColorBalance(10, -10, -10),
		"color_func": gift.ColorFunc(
			func(r0, g0, b0, a0 float32) (r, g, b, a float32) {
				r = 1 - r0   // invert the red channel
				g = g0 + 0.1 // shift the green channel by 0.1
				b = 0        // set the blue channel to 0
				a = a0       // preserve the alpha channel
				return r, g, b, a
			},
		),
		"convolution_emboss": gift.Convolution(
			[]float32{
				-1, -1, 0,
				-1, 1, 1,
				0, 1, 1,
			},
			false, false, false, 0.0,
		),
	}

	for name, filter := range filters {
		g := gift.New(filter)
		dst := image.NewNRGBA(g.Bounds(src.Bounds()))
		g.Draw(dst, src)
		saveImage("testdata/dst_"+name+".png", dst)
	}
}

func loadImage(filename string) image.Image {
	f, err := os.Open(filename)
	if err != nil {
		log.Fatalf("os.Open failed: %v", err)
	}
	defer f.Close()
	img, _, err := image.Decode(f)
	if err != nil {
		log.Fatalf("image.Decode failed: %v", err)
	}
	return img
}

func saveImage(filename string, img image.Image) {
	f, err := os.Create(filename)
	if err != nil {
		log.Fatalf("os.Create failed: %v", err)
	}
	defer f.Close()
	err = png.Encode(f, img)
	if err != nil {
		log.Fatalf("png.Encode failed: %v", err)
	}
}
Issues
  • Sepia takes a parameter for amount

    Sepia takes a parameter for amount

    The Change

    This change makes allows Sepia to accept a paramter for how much it is applied.

    Demo

    Here's an unaltered images:

    original

    And here's that image going through 0 to 100 in steps of 10:

    sepia-demo

    Why

    CamanJS has some really nice filters that I would like to port over to go to see how performance compares. Many of these filters make use of sepia with a paramter for how much it should be applied.

    opened by nixterrimus 9
  • Animated GIF transparency issue

    Animated GIF transparency issue

    Hi, I wasn't sure where the best place to post this was since I'm not sure if it's a bug or if I'm just doing something silly. If this is the wrong forum I apologise.

    I've been working on a little HTTP API that builds on gift (https://github.com/paddycarey/ims) and it's working great for PNG and JPEG images, but I've run into an issue when applying filters to animated GIF images. It seems that transparency is not preserved in the filtered frames and it results in large black areas that should really be transparent since they haven't changed since the previous frame.

    This is maybe easier to explain with an example.

    package main
    
    import (
        "fmt"
        "image"
        "image/gif"
        "os"
        "runtime"
    
        "github.com/disintegration/gift"
    )
    
    func main() {
    
        runtime.GOMAXPROCS(runtime.NumCPU())
    
        f, err := os.Open("test.gif")
        if err != nil {
            panic(err)
        }
        defer f.Close()
    
        g, err := gif.DecodeAll(f)
        if err != nil {
            panic(err)
        }
    
        filter := gift.New(
            gift.FlipHorizontal(),
        )
    
        newImages := []*image.Paletted{}
        for _, i := range g.Image {
            dst := image.NewPaletted(filter.Bounds(i.Bounds()), i.Palette)
            filter.Draw(dst, i)
            newImages = append(newImages, dst)
        }
        g.Image = newImages
    
        of, err := os.Create("out.gif")
        if err != nil {
            panic(err)
        }
        defer of.Close()
    
        err = gif.EncodeAll(of, g)
        if err != nil {
            panic(err)
        }
    
        fmt.Println("Successfully encoded gif: out.gif")
    }
    

    Used with the following test image: test

    Produces the following output: out

    I looked around and found some similar issues, I thought it may be the same as this issue, it's certainly got the same symptoms, but I'm not sure. I'm able to run DecodeAll and EncodeAll and the result will be fine, provided I don't use gift. For what it's worth I also tested with imaging and it has the same issue.

    go version returns go1.4.1 linux/amd64 if that helps.

    Thanks again for the great library, any help you could provide would be greatly appreciated.

    opened by paddycarey 8
  • whiteboard cleaner

    whiteboard cleaner

    I stumble on gift yesterday and I was wondering if it is already at a point where I could use it to replace this one liner

    #!/bin/bash
    convert "$1" -morphology Convolve DoG:15,100,0 -negate -normalize -blur 0x1 -channel RBG -level 60%,91%,0.1 "$2"
    

    If this is not the right place to ask question about this lib please let me know what is the best venue.

    Thanks

    opened by yml 8
  • DrawAt with OverOperator - White border around transparent background image

    DrawAt with OverOperator - White border around transparent background image

    First off, this is a great library. I have been using gift with great results. Props to the author(s).

    This issue is in regards to a white border rendered around images with a transparent background when using DrawAt with the OverOperator to write the image onto another image. My intent is to have transparent pngs render with no white border on top of other images.

    Is this result the intended functionality of the OverOperator functionality? Is there any strategy I can take to get around this?

    Example code below:

    package main
    
    import (
        "image"
        "image/color"
        "image/draw"
        "image/png"
        "os"
    
        "github.com/disintegration/gift"
    )
    
    func main() {
        f, err := os.Open("test.png")
        if err != nil {
            panic(err)
        }
        defer f.Close()
    
        srcImg, _, err := image.Decode(f)
        if err != nil {
            panic(err)
        }
    
        finalImg := image.NewRGBA(image.Rect(0, 0, 300, 300))
    
        //draw background color (dk blue) on final image
        bgColor := color.RGBA{0, 0, 100, 255}
        draw.Draw(finalImg, finalImg.Bounds(), &image.Uniform{bgColor}, image.ZP, draw.Src)
    
        gift.New().DrawAt(finalImg, srcImg, image.Point{0, 0}, gift.OverOperator)
    
        fOut, err := os.Create("output.png")
        if err != nil {
            panic(err)
        }
    
        png.Encode(fOut, finalImg)
    }
    

    Source transparent background png:

    test

    Output image:

    output

    opened by justenPalmer 6
  • Feature Request: Arbitrary Rotation

    Feature Request: Arbitrary Rotation

    I'd love to see something along the lines of php's imagerotate which allows arbitrary angles for rotation along with a parameter for the color of the padding. I haven't seen it in any go inserted manip libraries and it would be great!

    enhancement 
    opened by donatj 3
  • Travis-ci: added support for ppc64le & updated 1.13, 1.14 & 1.15 go versions

    Travis-ci: added support for ppc64le & updated 1.13, 1.14 & 1.15 go versions

    Signed-off-by: Devendranath Thadi [email protected]

    Added power support for the travis.yml file with ppc64le and updated latest 1.13, 1.14 & 1.15 go versions. This is part of the Ubuntu distribution for ppc64le. This helps us simplify testing later when distributions are re-building and re-releasing.

    opened by dthadi3 2
  • Tests error on aarch64, ppc64le, s390x

    Tests error on aarch64, ppc64le, s390x

    Golang 1.12.6 on aarch64, ppc64le, s390x:

    Testing    in: /builddir/build/BUILD/gift-1.2.0/_build/src
             PATH: /builddir/build/BUILD/gift-1.2.0/_build/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/sbin
           GOPATH: /builddir/build/BUILD/gift-1.2.0/_build:/usr/share/gocode
      GO111MODULE: off
          command: go test -buildmode pie -compiler gc -ldflags "-X github.com/disintegration/gift/version=1.2.0 -extldflags '-Wl,-z,relro -Wl,--as-needed  -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld '"
          testing: github.com/disintegration/gift
    github.com/disintegration/gift
    --- FAIL: TestBrightness (0.00s)
        colors_test.go:434: test [brightness (-30)] failed: image.Rectangle{Min:image.Point{X:0, Y:0}, Max:image.Point{X:5, Y:3}}, []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x14, 0x64, 0x54, 0x64, 0x14, 0x0, 0x34, 0x0, 0x34, 0x0}
    --- FAIL: TestGolden (0.61s)
        gift_test.go:593: resulting image differs from golden: contrast_increase
        gift_test.go:593: resulting image differs from golden: saturation_decrease
        gift_test.go:593: resulting image differs from golden: saturation_increase
        gift_test.go:593: resulting image differs from golden: hue_rotate
    FAIL
    
    opened by eclipseo 2
  • Feature request: trim function

    Feature request: trim function

    See the 'Trim' example in https://images.weserv.nl/#adjustments. It trims "boring" pixels from all edges that contain values within a similarity of the top-left pixel. So the excess of (for example) edged white space is removed. Useful to 'intelligently' crop an image of something against a even coloured background. The resulting image will be smaller but the informational part of the image will not change in any way.

    opened by Gys 2
  • Feature Request: Thresholding

    Feature Request: Thresholding

    Are there any plans to add thresholding to this library?

    I'm completely new to this field, but would be interested in helping out if we can discuss what the API would look like. Any thoughts?

    opened by saracen 2
  • Feature request: Perceptual hash

    Feature request: Perceptual hash

    It would be awesome to have this feature. Even simple average hash would be cool for the beginning. Just need int64 that represents visual hash of the image. Thank you!

    opened by ernado 2
  • Progressive JPEG defaults to baseline after processing

    Progressive JPEG defaults to baseline after processing

    Hi,

    I am using gift with hugo. It is awesome, but I noticed that all jpegs processed end up as baseline.

    Example:

    • original image: image

    • same image resized by hugo via gift: image

    The tool used above can be found here.

    Can this behavior be adjusted so that a progressive jpeg stays progressive after resize/filter?

    Thank you!

    opened by thelightstain 1
  • How add custom dither filter with paletted image

    How add custom dither filter with paletted image

    I implemented gift.Filter interface with method Draw below. But the result plain is white image only. Is there something wrong with my code? Or How to implement gift.Filter in the right way?

    func (f ditherFilter) Draw(dst draw.Image, src image.Image, options *gift.Options) {
    	dst = image.NewPaletted(src.Bounds(), color.Palette{color.Black, color.White})
    	draw.FloydSteinberg.Draw(dst, src.Bounds(), src, image.ZP)
    }
    

    reference: https://golang.org/pkg/image/draw/

    Thanks.

    opened by diantanjung 0
Owner
Grigory Dryapak
Grigory Dryapak
Image processing library and rendering toolkit for Go.

blend Image processing library and rendering toolkit for Go. (WIP) Installation: This library is compatible with Go1. go get github.com/phrozen/blend

Guillermo Estrada 59 Dec 24, 2021
An image server toolkit in Go (Golang)

Image Server An image server toolkit in Go (Golang) Features HTTP server Resize (GIFT, nfnt resize, Graphicsmagick) Rotate Crop Convert (JPEG, GIF (an

Pierre Durand 2k Jun 15, 2022
darkroom - An image proxy with changeable storage backends and image processing engines with focus on speed and resiliency.

Darkroom - Yet Another Image Proxy Introduction Darkroom combines the storage backend and the image processor and acts as an Image Proxy on your image

Gojek 192 Jun 6, 2022
Easily customizable Social image (or Open graph image) generator

fancycard Easily customizable Social image (or Open graph image) generator Built with Go, Gin, GoQuery and Chromedp Build & Run Simply, Clone this rep

Youngbin Han 4 Jan 14, 2022
An API which allows you to upload an image and responds with the same image, stripped of EXIF data

strip-metadata This is an API which allows you to upload an image and responds with the same image, stripped of EXIF data. How to run You need to have

Cristina Simionescu 0 Nov 25, 2021
Imgpreview - Tiny image previews for HTML while the original image is loading

imgpreview This is a Go program that generates tiny blurry previews for images t

Dmitry Chestnykh 8 May 22, 2022
gui toolkit for go

Simple GUI toolkit with go Install You will need to install gtk-dev files. go get github.com/zozor/hgui The idea This is a gui toolkit that relies on

Anders 58 Feb 14, 2021
Image processing algorithms in pure Go

bild A collection of parallel image processing algorithms in pure Go. The aim of this project is simplicity in use and development over absolute high

Anthony N. Simon 3.6k Jun 26, 2022
Go package for fast high-level image processing powered by libvips C library

bimg Small Go package for fast high-level image processing using libvips via C bindings, providing a simple programmatic API. bimg was designed to be

Tom 1.9k Jun 22, 2022
Decode embedded EXIF meta data from image files.

goexif Provides decoding of basic exif and tiff encoded data. Still in alpha - no guarantees. Suggestions and pull requests are welcome. Functionality

Robert Carlsen 522 Jun 24, 2022
A lightning fast image processing and resizing library for Go

govips A lightning fast image processing and resizing library for Go This package wraps the core functionality of libvips image processing library by

David Byttow 697 Jun 28, 2022
Fast, simple, scalable, Docker-ready HTTP microservice for high-level image processing

imaginary Fast HTTP microservice written in Go for high-level image processing backed by bimg and libvips. imaginary can be used as private or public

Tom 4.4k Jun 23, 2022
Imaging is a simple image processing package for Go

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

Grigory Dryapak 4.3k Jun 24, 2022
Pure golang image resizing

This package is no longer being updated! Please look for alternatives if that bothers you. Resize Image resizing for the Go programming language with

Jan Schlicht 2.8k Jun 26, 2022
smartcrop finds good image crops for arbitrary crop sizes

smartcrop smartcrop finds good image crops for arbitrary sizes. It is a pure Go implementation, based on Jonas Wagner's smartcrop.js Image: https://ww

Christian Muehlhaeuser 1.6k Jun 25, 2022
Go package for decoding and encoding TARGA image format

tga tga is a Go package for decoding and encoding TARGA image format. It supports RLE and raw TARGA images with 8/15/16/24/32 bits per pixel, monochro

Sigrid Solveig Haflínudóttir 30 Mar 5, 2022
:triangular_ruler: Create beautiful generative image patterns from a string in golang.

geopattern Create beautiful generative image patterns from a string in golang. Go port of Jason Long's awesome GeoPattern library. Read geopattern's d

Pravendra Singh 1.2k Jun 9, 2022
Go Perceptual image hashing package

goimagehash Inspired by imagehash A image hashing library written in Go. ImageHash supports: Average hashing Difference hashing Perception hashing Wav

Dong-hee Na 508 Jun 23, 2022
The imghdr module determines the type of image contained in a file for go

goimghdr Inspired by Python's imghdr Installation go get github.com/corona10/goimghdr List of return value Value Image format "rgb" SGI ImgLib Files

Dong-hee Na 38 Jan 23, 2022