How to crop a specific region from an image in Go?

To crop a specific region from an image in Go, you can use the github.com/nfnt/resize library and manipulate the image using the image and image/draw packages. Here's an example code to crop a region from an image:

package main import ( "fmt" "image" "image/draw" "os" "github.com/nfnt/resize" ) func main() { // Open the image file file, err := os.Open("input.jpg") if err != nil { fmt.Println("Error opening image file:", err) return } defer file.Close() // Decode the image file img, _, err := image.Decode(file) if err != nil { fmt.Println("Error decoding image file:", err) return } // Define the region to crop (x, y, width, height) cropRect := image.Rect(100, 100, 300, 300) // Create a new image of the desired size for cropping croppedImg := image.NewRGBA(cropRect) // Crop the region draw.Draw(croppedImg, croppedImg.Bounds(), img, cropRect.Min, draw.Src) // Resize the cropped image if needed resizedImg := resize.Resize(200, 200, croppedImg, resize.Lanczos3) // Save the cropped and resized image to a file outFile, err := os.Create("output.jpg") if err != nil { fmt.Println("Error creating output image file:", err) return } defer outFile.Close() // Encode the image as JPEG and save it if err := jpeg.Encode(outFile, resizedImg, nil); err != nil { fmt.Println("Error encoding and saving output image:", err) return } fmt.Println("Image cropped and saved successfully!") }

Make sure to install the github.com/nfnt/resize library by executing go get github.com/nfnt/resize before running the code.