Thursday, April 7, 2016

Go: imagick image croping after rotation problem

I need to load image rotate it by some angle, then crop some part of it. Seems trivial, isn't?

I use: gopkg.in/gographics/imagick.v2/imagick package.

Load image
iwand := imagick.NewMagickWand()
defer iwand.Destroy()
if err := iwand.ReadImage(s); err != nil {
 log.Panicf("cannot open image %s", err)
}
Rotate it, fill new area with yellow
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)
}
Calculate the position and size of the rectangle to cut
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)
Make the area red (with transparency), just for learning
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)
Crop and save to file
log.Printf("w,h,x,y: %d,%d,%d,%d", newW, newH, x, y)
if err := iwand.CropImage(newW, newH, x, y); err != nil {
 log.Fatalf("problem with crop: %s", err)
}
iwand.WriteImage(d)

Input file
Original image (from: https://en.wikipedia.org/wiki/Linux)

Output file
Image rotated and cropped

Need to repage!
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)
Rotated and cropped - fixed
Full source: gist