Skip to content

PHP: How to fix Image rotation issue in img tag because of EXIF?

Ayyaz Zafar1 min read

Photos captured by some smartphones especially iPhones are automatically rotated when we use it in <img> tag which is mostly not acceptable as we don’t need such unwanted rotation. This happens because of EXIF Data stored in that image. But we can easily fix it using PHP by following these steps:

PHP
function autorotate($src){// check if extension exists or notif(extension_loaded('imagick')){    try    {               $image= new Imagick($src);        switch ($image->getImageOrientation()) {        case Imagick::ORIENTATION_TOPLEFT:            break;        case Imagick::ORIENTATION_TOPRIGHT:            $image->flopImage();            break;        case Imagick::ORIENTATION_BOTTOMRIGHT:            $image->rotateImage("#000", 180);            break;        case Imagick::ORIENTATION_BOTTOMLEFT:            $image->flopImage();            $image->rotateImage("#000", 180);            break;        case Imagick::ORIENTATION_LEFTTOP:            $image->flopImage();            $image->rotateImage("#000", -90);            break;        case Imagick::ORIENTATION_RIGHTTOP:            $image->rotateImage("#000", 90);            break;        case Imagick::ORIENTATION_RIGHTBOTTOM:            $image->flopImage();            $image->rotateImage("#000", 90);            break;        case Imagick::ORIENTATION_LEFTBOTTOM:            $image->rotateImage("#000", -90);            break;        default: // Invalid orientation            break;      }      $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);      $image->stripImage(); // if you want to get rid of all EXIF data        $image->writeImage();        $image->clear();        $image->destroy();      return $image;    }    catch(Exception $e) {        return 'Exception caught: ',  $e->getMessage(), "";    }    }  else  {      return "Imagick extension is not installed.";  }}  // now run autorotate() function with source of file as parameterautorotate('my_img.jpg');

Or you can also fix it with just one line if you have root access to your linux server. Just run following shell command:

Text
convert image.jpg -auto-orient output.jpg

Latest tutorials

All 754 →

Get new tutorials by email

One email when something new is published. Unsubscribe anytime.

Written by Ayyaz Zafar, full-stack developer for 15+ years. Work with me