Skip to content

Instantly share code, notes, and snippets.

@orian orian/rotate_and_crop.go
Last active Apr 7, 2016

Embed
What would you like to do?
Demonstrate how to rotate and then crop image.
// http://dev.pawelsz.eu/2016/04/go-imagick-image-croping-after-rotation.html
//
package main
import (
"gopkg.in/gographics/imagick.v2/imagick"
"log"
"math"
)
func minUint(a, b uint) uint {
if a < b {
return a
}
return b
}
func calcSize(w, h uint) uint {
return uint(math.Sqrt(2.) / 2. * float64(minUint(w, h)))
}
func main() {
s := "example.jpeg"
d := "example.cut.jpeg"
iwand := imagick.NewMagickWand()
defer iwand.Destroy()
if err := iwand.ReadImage(s); err != nil {
log.Panicf("cannot open image %s", err)
}
w := iwand.GetImageWidth()
h := iwand.GetImageHeight()
log.Printf("old size: %d,%d", w, h)
pwand := imagick.NewPixelWand()
pwand.SetColor("yellow")
if err := iwand.RotateImage(pwand, 45); err != nil {
log.Panicf("problem with rotation: %s", err)
}
newW := calcSize(w, h)
newH := newW
w = iwand.GetImageWidth()
h = iwand.GetImageHeight()
log.Printf("new size: %d,%d", w, h)
x := int((w - newW) / 2)
y := int((h - newH) / 2)
// draw red rectangle around the area
dwand := imagick.NewDrawingWand()
pwand.SetColor("red")
pwand.SetOpacity(0.5)
dwand.SetFillColor(pwand)
dwand.Rectangle(float64(x), float64(y), float64(newW+uint(x)), float64(newH+uint(y)))
iwand.DrawImage(dwand)
log.Printf("w,h,x,y: %d,%d,%d,%d", newW, newH, x, y)
iwand.ResetImagePage("")
if err := iwand.CropImage(newW, newH, x, y); err != nil {
log.Fatalf("problem with crop: %s", err)
}
iwand.WriteImage(d)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.