Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageMagick convert rotate crop

The rotate option in ImageMagick's convert tool rotates the image but adds background color to fill the gaps.

I'm looking for a way to rotate and then crop the largest rectangle containing content of the image. Is it possible with convert?

Edited by Mark Setchell...

So, if your original rectangle is a checkerboard created like this:

convert -size 512x512 pattern:checkerboard a.png

enter image description here

and you rotate it through 20 degrees like this

convert -background fuchsia -rotate 20 a.png b.png

enter image description here

you want the largest rectangle that fits on the checkerboard and contains no pink?

like image 707
Mohammad Moghimi Avatar asked Mar 24 '15 22:03

Mohammad Moghimi


2 Answers

You can get an approximation of your expected result by using +repage and replacing -rotate with -distort ScaleRotateTranslate:

convert -background fuchsia -distort ScaleRotateTranslate 20 +repage a.png b.png

Result

like image 144
bfontaine Avatar answered Oct 20 '22 01:10

bfontaine


After creating the image as indicated:

convert -size 512x512 pattern:checkerboard a.png

This seems to do the work:

angle=20
ratio=`convert a.png -format \
     "%[fx:aa=$angle*pi/180; min(w,h)/(w*abs(cos(aa))+h*abs(sin(aa)))]" \
     info:`
crop="%[fx:floor(w*$ratio)]x%[fx:floor(h*$ratio)]"
crop="$crop+%[fx:ceil((w-w*$ratio)/2)]+%[fx:ceil((h-h*$ratio)/2)]"
convert a.png -set option:distort:viewport "$crop" \
          +distort SRT $angle +repage   rotate_internal.png

From here.

like image 32
Ivan Chaer Avatar answered Oct 19 '22 23:10

Ivan Chaer