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.Image, because a useful Go habit is to accept interfaces and return concrete types -
image bounds don't have to start at (0,0), so for the source image we ask for its bounding rectangle. We create the destination image ourselves, so its bounds start at (0,0)
-
the scaling interface is generic and, as a result, somewhat complicated. Package
drawis, at its core, a compositing engine which draws bitmap images with a specific operation.draw.Overdraws one image over another, optionally using a mask -
resizing is implemented by the
Scalerinterface, which takes a destination image, a rectangle within that image, a source image, and a rectangle within the source, and paints the source rectangle into the destination rectangle. Resizing happens when the destination rectangle has different dimensions than the 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 quality
-
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.