Welcome to our new website! Some content may have moved. If you can’t find what you need, try our search or get in touch and we’ll be happy to help.

Speak to a website designer — call Call 01793 239239 Our team are here 9am to 5pm weekdays Client Connect

The Digital Insider Blog

Fixing photo orientation on images uploaded via PHP

Fixing photo orientation on images uploaded via PHP

Great function (created by Wes over on Stack Overflow) that can be used to automatically correct the image orientation when uploading images.

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);
Keep reading

Related posts

Need a hand with your website?

Get in touch and we'll be happy to help — no tricks, traps or technobabble.