10

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?

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
Mohammad Moghimi
  • 4,636
  • 14
  • 50
  • 76

2 Answers2

6

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

bfontaine
  • 18,169
  • 13
  • 73
  • 107
5

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.

Ivan Chaer
  • 6,980
  • 1
  • 38
  • 48