# Rotating an image if the height is larger than width?

I would like to rotate an image if and only if, the aspect ratio of the image is > 1, else just print the original picture and afterwards use the data.

My problem is that Mathematica writes "expecting an image instead of null", because of the If statement.

• I don't see any code you've written. In any event, what you can do is have the second argument of ImageRotate[] be a conditional. Oct 13 '15 at 9:19

Here's one method you can try, although you don't specify exactly how you would like the image to be rotated - you can edit the 90 Degree angle to your own requirements.

test = ImageResize[ExampleData[{"TestImage", "Mandrill"}], {256, 256}];
crop = ImageCrop[test, {128, 256}]


rotateImage = ImageRotate[#, If[ImageAspectRatio[#] > 1, 90 Degree, 0]] &;
rotateImage[crop]


## Edit

A comment suggests a different order for the rotation function, which doesn't call ImageRotate[] unnecessarily, namely:

rotateImage2 = If[ImageAspectRatio@# > 1, ImageRotate[#, 90 Degree], #] &;


This avoids a performance overhead if no rotation is required, since image is faster than ImageRotate[image, 0 Degree].

• Why not use ImageAspectRatio[]? Oct 13 '15 at 9:29
• @J.M. because I forgot about that one? Now changed :-) Oct 13 '15 at 9:30
• …upvoted now. :) Oct 13 '15 at 12:59
• I would do it the other way round to prevent an unnecessary call to ImageRotate if no rotation is needed: rotateImage = If[ImageAspectRatio@#>1,ImageRotate[#,90 Degree],#]& as If has the HoldRest attribute. Oct 13 '15 at 13:52
• Can't test that, I'm afraid, our license server suddenly died :( I do recall, that image-manipulating functions tend to be slow. Oct 13 '15 at 14:06