README.md

  1# GO IMAGE FILTERING TOOLKIT (GIFT)
  2
  3[![GoDoc](https://godoc.org/github.com/disintegration/gift?status.svg)](https://godoc.org/github.com/disintegration/gift)
  4[![Build Status](https://travis-ci.org/disintegration/gift.svg?branch=master)](https://travis-ci.org/disintegration/gift)
  5[![Coverage Status](https://coveralls.io/repos/github/disintegration/gift/badge.svg?branch=master)](https://coveralls.io/github/disintegration/gift?branch=master)
  6
  7*Package gift provides a set of useful image processing filters.*
  8
  9Pure Go. No external dependencies outside of the Go standard library.
 10
 11
 12### INSTALLATION / UPDATING
 13
 14    go get -u github.com/disintegration/gift
 15
 16
 17### DOCUMENTATION
 18
 19http://godoc.org/github.com/disintegration/gift
 20
 21
 22### QUICK START
 23
 24```go
 25// 1. Create a new GIFT filter list and add some filters:
 26g := gift.New(
 27	gift.Resize(800, 0, gift.LanczosResampling),
 28	gift.UnsharpMask(1, 1, 0),
 29)
 30
 31// 2. Create a new image of the corresponding size.
 32// dst is a new target image, src is the original image
 33dst := image.NewRGBA(g.Bounds(src.Bounds()))
 34
 35// 3. Use Draw func to apply the filters to src and store the result in dst:
 36g.Draw(dst, src)
 37``` 
 38
 39### USAGE
 40
 41To create a sequence of filters, the `New` function is used:
 42```go
 43g := gift.New(
 44	gift.Grayscale(),
 45	gift.Contrast(10),
 46)
 47```
 48Filters also can be added using the `Add` method:
 49```go
 50g.Add(GaussianBlur(2)) 
 51```
 52
 53The `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). 
 54
 55```go
 56dst := image.NewRGBA(g.Bounds(src.Bounds()))
 57```
 58
 59There are two methods available to apply these filters to an image:
 60
 61- `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).
 62```go
 63g.Draw(dst, src)
 64```
 65
 66- `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:
 67```go
 68g.DrawAt(dst, src, dst.Bounds().Min, gift.CopyOperator)
 69```
 70
 71Two image composition operators are supported by now:
 72- `CopyOperator` - Replaces pixels of the dst image with pixels of the filtered src image. This mode is used by the Draw method.
 73- `OverOperator` - Places the filtered src image on top of the dst image. This mode makes sence if the filtered src image has transparent areas.
 74
 75Empty filter list can be used to create a copy of an image or to paste one image to another. For example:
 76```go
 77// Create a new image with dimensions of the bgImage.
 78dstImage := image.NewRGBA(bgImage.Bounds())
 79// Copy the bgImage to the dstImage.
 80gift.New().Draw(dstImage, bgImage)
 81// Draw the fgImage over the dstImage at the (100, 100) position.
 82gift.New().DrawAt(dstImage, fgImage, image.Pt(100, 100), gift.OverOperator)
 83```
 84
 85
 86### SUPPORTED FILTERS
 87
 88+ Transformations
 89
 90    - Crop(rect image.Rectangle)
 91    - CropToSize(width, height int, anchor Anchor)
 92    - FlipHorizontal()
 93    - FlipVertical()
 94    - Resize(width, height int, resampling Resampling)
 95    - ResizeToFill(width, height int, resampling Resampling, anchor Anchor)
 96    - ResizeToFit(width, height int, resampling Resampling)
 97    - Rotate(angle float32, backgroundColor color.Color, interpolation Interpolation)
 98    - Rotate180()
 99    - Rotate270()
100    - Rotate90()
101    - Transpose()
102    - Transverse()
103    
104+ Adjustments & effects
105
106    - Brightness(percentage float32)
107    - ColorBalance(percentageRed, percentageGreen, percentageBlue float32)
108    - ColorFunc(fn func(r0, g0, b0, a0 float32) (r, g, b, a float32))
109    - Colorize(hue, saturation, percentage float32)
110    - ColorspaceLinearToSRGB()
111    - ColorspaceSRGBToLinear()
112    - Contrast(percentage float32)
113    - Convolution(kernel []float32, normalize, alpha, abs bool, delta float32)
114    - Gamma(gamma float32)
115    - GaussianBlur(sigma float32)
116    - Grayscale()
117    - Hue(shift float32)
118    - Invert()
119    - Maximum(ksize int, disk bool)
120    - Mean(ksize int, disk bool)
121    - Median(ksize int, disk bool)
122    - Minimum(ksize int, disk bool)
123    - Pixelate(size int)
124    - Saturation(percentage float32)
125    - Sepia(percentage float32)
126    - Sigmoid(midpoint, factor float32)
127    - Sobel()
128    - Threshold(percentage float32)
129    - UnsharpMask(sigma, amount, threshold float32)
130
131
132### FILTER EXAMPLES
133
134The original image:
135
136![](testdata/src.png) 
137
138Resulting images after applying some of the filters:
139
140 name / result                              | name / result                              | name / result                              | name / result
141--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------
142resize                                      | crop_to_size                               | rotate_180                                 | rotate_30
143![](testdata/dst_resize.png)                | ![](testdata/dst_crop_to_size.png)         | ![](testdata/dst_rotate_180.png)           | ![](testdata/dst_rotate_30.png)
144brightness_increase                         | brightness_decrease                        | contrast_increase                          | contrast_decrease
145![](testdata/dst_brightness_increase.png)   | ![](testdata/dst_brightness_decrease.png)  | ![](testdata/dst_contrast_increase.png)    | ![](testdata/dst_contrast_decrease.png)
146saturation_increase                         | saturation_decrease                        | gamma_1.5                                  | gamma_0.5
147![](testdata/dst_saturation_increase.png)   | ![](testdata/dst_saturation_decrease.png)  | ![](testdata/dst_gamma_1.5.png)            | ![](testdata/dst_gamma_0.5.png)
148gaussian_blur                               | unsharp_mask                               | sigmoid                                    | pixelate
149![](testdata/dst_gaussian_blur.png)         | ![](testdata/dst_unsharp_mask.png)         | ![](testdata/dst_sigmoid.png)              | ![](testdata/dst_pixelate.png)
150colorize                                    | grayscale                                  | sepia                                      | invert
151![](testdata/dst_colorize.png)              | ![](testdata/dst_grayscale.png)            | ![](testdata/dst_sepia.png)                | ![](testdata/dst_invert.png)
152mean                                        | median                                     | minimum                                    | maximum
153![](testdata/dst_mean.png)                  | ![](testdata/dst_median.png)               | ![](testdata/dst_minimum.png)              | ![](testdata/dst_maximum.png)
154hue_rotate                                  | color_balance                              | color_func                                 | convolution_emboss
155![](testdata/dst_hue_rotate.png)            | ![](testdata/dst_color_balance.png)        | ![](testdata/dst_color_func.png)           | ![](testdata/dst_convolution_emboss.png)
156
157Here's the code that produces the above images:
158
159```go
160package main
161
162import (
163	"image"
164	"image/color"
165	"image/png"
166	"log"
167	"os"
168
169	"github.com/disintegration/gift"
170)
171
172func main() {
173	src := loadImage("testdata/src.png")
174
175	filters := map[string]gift.Filter{
176		"resize":               gift.Resize(100, 0, gift.LanczosResampling),
177		"crop_to_size":         gift.CropToSize(100, 100, gift.LeftAnchor),
178		"rotate_180":           gift.Rotate180(),
179		"rotate_30":            gift.Rotate(30, color.Transparent, gift.CubicInterpolation),
180		"brightness_increase":  gift.Brightness(30),
181		"brightness_decrease":  gift.Brightness(-30),
182		"contrast_increase":    gift.Contrast(30),
183		"contrast_decrease":    gift.Contrast(-30),
184		"saturation_increase":  gift.Saturation(50),
185		"saturation_decrease":  gift.Saturation(-50),
186		"gamma_1.5":            gift.Gamma(1.5),
187		"gamma_0.5":            gift.Gamma(0.5),
188		"gaussian_blur":        gift.GaussianBlur(1),
189		"unsharp_mask":         gift.UnsharpMask(1, 1, 0),
190		"sigmoid":              gift.Sigmoid(0.5, 7),
191		"pixelate":             gift.Pixelate(5),
192		"colorize":             gift.Colorize(240, 50, 100),
193		"grayscale":            gift.Grayscale(),
194		"sepia":                gift.Sepia(100),
195		"invert":               gift.Invert(),
196		"mean":                 gift.Mean(5, true),
197		"median":               gift.Median(5, true),
198		"minimum":              gift.Minimum(5, true),
199		"maximum":              gift.Maximum(5, true),
200		"hue_rotate":           gift.Hue(45),
201		"color_balance":        gift.ColorBalance(10, -10, -10),
202		"color_func": gift.ColorFunc(
203			func(r0, g0, b0, a0 float32) (r, g, b, a float32) {
204				r = 1 - r0   // invert the red channel
205				g = g0 + 0.1 // shift the green channel by 0.1
206				b = 0        // set the blue channel to 0
207				a = a0       // preserve the alpha channel
208				return
209			},
210		),
211		"convolution_emboss": gift.Convolution(
212			[]float32{
213				-1, -1, 0,
214				-1, 1, 1,
215				0, 1, 1,
216			},
217			false, false, false, 0.0,
218		),
219	}
220
221	for name, filter := range filters {
222		g := gift.New(filter)
223		dst := image.NewNRGBA(g.Bounds(src.Bounds()))
224		g.Draw(dst, src)
225		saveImage("testdata/dst_"+name+".png", dst)
226	}
227}
228
229func loadImage(filename string) image.Image {
230	f, err := os.Open(filename)
231	if err != nil {
232		log.Fatalf("os.Open failed: %v", err)
233	}
234	img, _, err := image.Decode(f)
235	if err != nil {
236		log.Fatalf("image.Decode failed: %v", err)
237	}
238	return img
239}
240
241func saveImage(filename string, img image.Image) {
242	f, err := os.Create(filename)
243	if err != nil {
244		log.Fatalf("os.Create failed: %v", err)
245	}
246	err = png.Encode(f, img)
247	if err != nil {
248		log.Fatalf("png.Encode failed: %v", err)
249	}
250}
251```