Golang image.Rectangle type and Rect function example

package image

 type Rectangle struct {
 Min, Max Point
 }

A Rectangle contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y. It is well-formed if Min.X <= Max.X and likewise for Y. Points are always well-formed. A rectangle's methods always return well-formed outputs for well-formed inputs.

Golang image.Rectangle type and Rect function usage example

 package main

 import (
 "fmt"
 "github.com/disintegration/imaging"
 "image"
 "os"
 "runtime"
 )

 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)
 }

 // define a rectangle
 rect := image.Rect(0, 0, 500, 500) <--------------- here
 fmt.Println("Min X : ", rect.Min.X)
 fmt.Println("Max X : ", rect.Max.X)

 // 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")

 }

Output :

Min X : 0

Max X : 500

Done

References :

http://golang.org/pkg/image/#Rectangle

http://golang.org/pkg/image/#Rect

Advertisement