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

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:

function autorotate($src)
{
// check if extension exists or not
if(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(), "\n";
    }  
  }
  else
  {
      return "Imagick extension is not installed.";
  }
}
  

// now run autorotate() function with source of file as parameter
autorotate('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:

convert image.jpg -auto-orient output.jpg

 

Leave a Reply

Your email address will not be published. Required fields are marked *