Skip to content

Instantly share code, notes, and snippets.

@andrewlkho
Last active October 24, 2021 00:28
Show Gist options
  • Save andrewlkho/9943921 to your computer and use it in GitHub Desktop.
Save andrewlkho/9943921 to your computer and use it in GitHub Desktop.
Lossless JPEG rotation

This was originally posted on 2007-03-17 to http://andrewho.co.uk/weblog/lossless-jpeg-rotation

I've been going through photos from Halfway Hall, and a lot of them have been taken vertically. The Canon camera I use (a compact) has a gravity sensor that can autorotate photos for you as it writes them; the way it does this is by using an EXIF tag which tells you how the image should be oriented. For example, if I take a picture with the camera rotated by 90 degrees:

% identify -format '%[EXIF:Orientation]' ./IMG_1120.JPG
6

The problem with this is that a lot of programs (Safari, for example) don't understand or respect this. What we really want to do is set the EXIF tag to 1 (essentially meaning "normal orientation"), and then rotate the picture itself. If the camera has already determined the correct orientation, as described above, then jHead can be used:

% jhead -autorot ./IMG_1120.JPG

This will losslessly rotate the image according to the EXIF-assigned orientation, and then reset that tag to 1.

If, on the other hand, the camera hasn't got that feature, so you actually want to rotate the image yourself, then jpegtran (which is actually what jHead uses) comes in handy. Don't forget to preserve the EXIF data with -copy all:

% jpegtran -rotate 90 -copy all ./IMG_1120.JPG > ./IMG_1120r.JPG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment