You are here

function image_gd_imagecache_autorotate in ImageCache Actions 7

Same name and namespace in other branches
  1. 8 autorotate/imagecache_autorotate.module \image_gd_imagecache_autorotate()

GD toolkit specific implementation of this image effect.

Parameters

stdClass $image:

Return value

bool true on success, false otherwise.

File

autorotate/imagecache_autorotate.module, line 127
Autorotate image based on EXIF Orientation tag.

Code

function image_gd_imagecache_autorotate(stdClass $image) {
  if (!function_exists('exif_read_data')) {
    watchdog('imagecache_actions', 'Image %file could not be auto-rotated: !message', array(
      '%file' => $image->source,
      '!message' => t('The exif_read_data() function is not available in this PHP installation. You probably have to enable the exif extension.'),
    ));
    return FALSE;
  }

  // Read and check result.
  $path = drupal_realpath($image->source);
  if ($path) {
    $exif = @exif_read_data($path);
  }
  else {

    // drupal_realpath and exif fail for remote file systems like S3.
    // Copy to a local temporary folder and retry.
    $base = drupal_basename($image->source);
    $uniq = md5(microtime() . $image->source);
    $path = file_directory_temp() . '/' . $uniq . '-' . $base;
    file_unmanaged_copy($image->source, $path);
    $exif = @exif_read_data($path);

    // Cleanup so we don't leave files behind.
    // The server would get them later on a reboot, but who knows when that
    // would be.
    file_unmanaged_delete($path);
  }
  if ($exif === FALSE) {
    watchdog('imagecache_actions', 'Image %file could not be auto-rotated: !message', array(
      '%file' => $image->source,
      '!message' => t('The exif_read_data() function returned FALSE.'),
    ));
    return FALSE;
  }
  if (isset($exif['Orientation'])) {

    // http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html:
    // 1 = Horizontal (normal)
    // 2 = Mirror horizontal
    // 3 = Rotate 180
    // 4 = Mirror vertical
    // 5 = Mirror horizontal and rotate 270 CW
    // 6 = Rotate 90 CW
    // 7 = Mirror horizontal and rotate 90 CW
    // 8 = Rotate 270 CW
    // @todo: Add horizontal and vertical flips etc.
    // imagecopy seems to be able to mirror, see conmments on
    // http://php.net/manual/en/function.imagecopy.php
    // @todo: Create sample set for tests.
    switch ($exif['Orientation']) {
      case 3:
        $degrees = 180;
        break;
      case 6:
        $degrees = 90;
        break;
      case 8:
        $degrees = 270;
        break;
      default:
        $degrees = 0;
    }
    if ($degrees != 0) {
      return image_rotate($image, $degrees);
    }
  }
  return TRUE;
}