fixing-photo-orientation-on-images-uploaded-via-php-from-ios-devices.jpeg

Below is a great function (created by Wes over on Stack Overflow) that can be used to automatically correct the image orientation when uploading images (the main culprit for weird orientation related glitches being iOS based devices) – simple call the correctImageOrientation() function after uploading the image and voilla the rotation/orientation of the image is corrected!

The function:

function correctImageOrientation($filename) {
  if (function_exists('exif_read_data')) {
    $exif = exif_read_data($filename);
    if($exif && isset($exif['Orientation'])) {
      $orientation = $exif['Orientation'];
      if($orientation != 1){
        $img = imagecreatefromjpeg($filename);
        $deg = 0;
        switch ($orientation) {
          case 3:
            $deg = 180;
            break;
          case 6:
            $deg = 270;
            break;
          case 8:
            $deg = 90;
            break;
        }
        if ($deg) {
          $img = imagerotate($img, $deg, 0);       
        }
        // then rewrite the rotated image back to the disk as $filename
        imagejpeg($img, $filename, 95);
      } // if there is some rotation necessary
    } // if have the exif orientation info
  } // if function exists     
}

Calling the function:

move_uploaded_file($uploadedFile, $destinationFilename);
correctImageOrientation($destinationFilename);

Feeling social? Share this with friends and colleagues...

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on skype
Skype
Share on whatsapp
WhatsApp
Share on email
Email