Golang : Crop image
This is a continuation from the previous tutorial on how to resize image in Golang. For this tutorial, we will learn how easy it is to crop image with the excellent https://github.com/disintegration/imaging package.
This code below will create two images. One which is cropped from center point and another cropped according to the defined rectangular region.
package main
import (
"fmt"
"github.com/disintegration/imaging"
"os"
"runtime"
"image"
)
func main() {
// maximize CPU usage for maximum performance
runtime.GOMAXPROCS(runtime.NumCPU())
// load original image
img, err := imaging.Open("./big.jpg")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// crop from center
centercropimg := imaging.CropCenter(img, 300, 300)
// save cropped image
err = imaging.Save(centercropimg, "./centercrop.jpg")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// crop out a rectangular region
rectcropimg := imaging.Crop(img, image.Rect(0, 0, 500, 500))
// save cropped image
err = imaging.Save(rectcropimg, "./rectcrop.jpg")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// everything ok
fmt.Println("Done")
}
Big.jpg(original)
Centercrop.jpg
Rectcrop.jpg
For more information and other functions to manipulate images, please see http://godoc.org/github.com/disintegration/imaging
See also : Golang : Resize Image
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.9k Golang : Scan forex opportunities by Bollinger bands
+9.7k Golang : Compare files modify date example
+20.9k Golang : Encrypt and decrypt data with TripleDES
+8.9k Mac OSX : Get a process/daemon status information
+5.8k Golang : How to write backslash in string?
+5.6k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+7.9k Golang : Oanda bot with Telegram and RSI example
+40.5k Golang : How to check if a string contains another sub-string?
+5k Swift : Convert string array to array example
+26.9k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+16.9k Golang : Get future or past hours, minutes or seconds
+15k Golang : Get digits from integer before and after given position example