Skip to content

Instantly share code, notes, and snippets.

@orian
Last active April 7, 2016 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orian/36dfc5bd622102b87f6e140d4e65379c to your computer and use it in GitHub Desktop.
Save orian/36dfc5bd622102b87f6e140d4e65379c to your computer and use it in GitHub Desktop.
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