RackPull

Wrong Exif thumbnail orientation in PHP

There are some JPEGs with Exif thumbnails that exif_thumbnail() interprets to be landscape (160 x 120) when they are supposed to be portrait (120 x 160). Here is a way to fix the dimensions in such cases:

<?php
  $filename = 'photo.jpg';
  list($width, $height) = getimagesize($filename);
  $thumb = exif_thumbnail($filename, $thumb_width, $thumb_height);

  // if the orientation of the image and its thumb are different, swap the
  // thumb dimensions
  if (($width < $height && $thumb_width > $thumb_height)
      || ($width > $height && $thumb_width < $thumb_height)) {
    $temp = $thumb_width;
    $thumb_width = $thumb_height;
    $thumb_height = $temp;
  }
?>