Resizing images
suggest changeThere are several libraries for resizing images in Go. Package golang.org/x/image/draw is one of the options:
func resize(src image.Image, dstSize image.Point) *image.RGBA {
srcRect := src.Bounds()
dstRect := image.Rectangle{
Min: image.Point{0, 0},
Max: dstSize,
}
dst := image.NewRGBA(dstRect)
draw.CatmullRom.Scale(dst, dstRect, src, srcRect, draw.Over, nil)
return dst
}
Notable points:
- we return
image.RGBA, notimage.Imagebecause Go's best practice is to accept interface as arguments to functions, but return concrete types - image bounds don't have to start at (0,0) so for the source image we ask for bounding rectangle. We create destination image ourselves so we create bounds that start at (0,0)
- scaling interface is very generic and as a result somewhat complicated. Package
drawis, at its core, a compositing engine which allows compositing (drawing) bitmap images with a specific operation.draw.Overis an operation that draws one image over another, optionally using a mask. - resizing is implementing as
Scalerinterface which takes destination image, a rectangle within destination image, source image, a rectangle within source images and paints source rectangle into destination rectangle. Resizing happens when destination rectangle has different dimension that source rectangle - the package implements 4 different scaling algorithms:
- nearest neighbor - fast, low quality
- approximate bi-linear - slower, better quality
- bi-linear - even slower, high quality
- catmull-rom - slowest, highest qulity
draw.CatmullRomis a global variable for an instance implementing catmull-rom algorithm. Other algorithms are available asdraw.NearestNeighbor,draw.ApproxBiLinearanddraw.BiLinearpackage global variables- putting it all together: to resize a source image to a given size, we create a destination image of desired size and use
Scalemethod of one of the global scalers to paint source image into a destination, with resizing being a side effect of using a scaler.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents