EXIF goodness

acme on 2003-01-03T15:22:48

The cool Ixus v3 I got for Christmas has a neat feature: intelligent orientation.

When I learnt about this I thought it'd be wonderful - when I put photos online, having to rotate images is a pain. However, the camera doesn't actually rotate the image, all it does it set a flag in the EXIF header. Perl comes to the rescue, as does jpegtran. It'd be silly if I rotated photos by decompressing the JPEG, rotating the image, and recompressing it. JPEG is lossy, so I'd lose quality. jpegtran exploits features of the JPEG spec allowing lossless rotation. Here's the script I knocked up:

#!/usr/bin/perl -w
use strict;
use File::Copy;
use File::Temp qw(:POSIX);
use Image::Info qw(image_info);
$| = 1;

foreach my $filename (@ARGV) {
  print "$filename... ";
  my $info = image_info($filename);
  my $orientation = $info->{Orientation}->[1];
  if ($orientation eq 'top_left') {
    print "not changing\n"
  } elsif ($orientation eq "right_top") {
    print "rotated right\n";
    my $tmp = tmpnam();
    system("jpegtran -copy all -rotate 90 $filename > $tmp") == 0
      or die "$?";
    move($tmp, $filename);
  } elsif ($orientation eq "left_bot") {
    print "rotated left\n";
    my $tmp = tmpnam();
    system("jpegtran -copy all -rotate 270 $filename > $tmp") == 0
      or die "$?";
    move($tmp, $filename);
  } else {
    print "unknown, not changed\n";
  }
}


Sweet

pudge on 2003-01-08T16:56:42

I do some similar stuff with rotation, but I manually figure out which ones need to be rotated. My Nikon Coolpix 995 apparently has the Orientation field (which I didn't know about), but it is always top_left. Drat! I thought this would be a timesaver for me. :-)

Writing back the changes of the orientation

tbms on 2003-01-26T21:13:52

Wouldn't it be better if the content of the field was changed while running the program. Currently the second run of the program turns all images that were turned further.

Re:Writing back the changes of the orientation

acme on 2003-01-26T21:17:14

Yup, I agree. At the time, I couldn't figure out how to get Image::Info to do this, however. Patches welcome!

Re:Writing back the changes of the orientation

flashfr on 2005-01-03T00:00:49

You can try exiftran instead of jpegtran :)

Debian's description :
  exiftran is a command line utility to transform digital image jpeg
  images. It can do lossless rotations like jpegtran, but unlike
  jpegtran it cares about the EXIF data: It can rotate images
  automatically by checking the exif orientation tag, it updates the
  exif informaton if needed (image dimension, orientation), it also
  rotates the exif thumbnail. It can process multiple images at once.