How to Resize and Crop Images in Go

TITLE: How to Resize and Crop Images in Go

TITLE: How to Resize and Crop Images in Go

Go's standard library does not include built-in image processing functions, so you must use the golang.org/x/image package to resize and crop images. Install the package and use Resize to change dimensions and Crop to extract a specific region.

package main

import (
	"image"
	"image/png"
	"os"
	"golang.org/x/image/draw"
)

func main() {
	// Load image
	f, err := os.Open("input.png")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	img, err := png.Decode(f)
	if err != nil {
		panic(err)
	}

	// Resize to 200x200
	rect := image.Rect(0, 0, 200, 200)
	resized := image.NewRGBA(rect)
	draw.BiLinear.Scale(resized, rect, img, img.Bounds(), draw.Over, nil)

	// Crop center 100x100
	bounds := resized.Bounds()
	cropRect := image.Rect(bounds.Dx()/2-50, bounds.Dy()/2-50, bounds.Dx()/2+50, bounds.Dy()/2+50)
	cropped := image.NewRGBA(image.Rect(0, 0, 100, 100))
	draw.Crop(cropped, cropped.Bounds(), resized, cropRect)

	// Save result
	out, err := os.Create("output.png")
	if err != nil {
		panic(err)
	}
	defer out.Close()

	if err := png.Encode(out, cropped); err != nil {
		panic(err)
	}
}

Run go get golang.org/x/image/draw before compiling.