ImageMagick Thumbnail Rotation

Summary: if you’re using ImageMagick on JPEG files with the -thumbnail option, you probably also want the -auto-orient option.


This is not a substantial post1, but I just wanted to document a minor point that I came across while making infrastructure upgrades to this website. You see, several of the posts on this website are quite image-heavy; I use ImageMagick to generate thumbnails for the images. This looks something like:

$ mogrify \
  -format jpg \
  -path thumbs \
  -thumbnail 300x300 \
  -quality 50 \
  image.jpg

However, this had the curious effect of rotating portrait images that were taken on my iPhone. For about a year I just accepted this as a mysterious effect, but I recently decided to figure out why.

It turns out that all pictures taken on an iPhone are actually in landscape orientation, in the sense that the pixels described by the underlying image data are oriented this way. Rotation is handled by EXIF metadata telling the viewer that “these pixels should be looked at sideways.” I think the reason for this is that JPEG is a lossy format. The camera itself takes landscape photographs; if these photographs are re-encoded in a different orientation (portrait), part of the original data will be lost. On the other hand, if you keep the underlying image data and encode the rotation in the metadata, there is obviously no loss of data.

However, the ImageMagick -thumbnail option strips most of the metadata, including the EXIF orientation data, which means that your image viewer has no clue what the orientation of the generated thumbnail should be.

You can check this with

$ identify -format '%[exif:orientation]' image.jpg

An orientation value of 1 means that the image was “properly” oriented, whereas another value means that the underlying image data should be viewed at a different orientation. Fortunately, ImageMagick also provides an easy way to fix the orientation before the EXIF metadata are stripped, by supplying the -auto-orient option. In this case, since generating thumbnails is extremely lossy anyway, it doesn’t really matter that we’re losing some image data by doing the rotation on the underlying image data.


  1. I’m trying to write one of those, but it’s a race against time till the start of the semester.↩︎


Comments

Submit a comment

Your comment will be held for moderation. If needed, I'll reach out to the provided email address with moderation updates. Your email will not be publicly displayed.

Note: comments are still in beta. Let me know if anything is broken!