Detect EXIF Orientation and Rotate Image using ImageMagick

PhpImagemagickExif

Php Problem Overview


Canon DSLRs appear to save photos in landscape orientation and uses exif::orientation to do the rotation.

Question: How can imagemagick be used to re-save the image into the intended orientation using the exif orientation data such that it no longer requires the exif data to display in the correct orientation?

Php Solutions


Solution 1 - Php

Use the auto-orient option of ImageMagick's convert to do this.

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

Or use mogrifyto do it in place

mogrify -auto-orient your-image.jpg

Solution 2 - Php

The PHP Imagick way would be to test the image orientation and rotate/flip the image accordingly:

function autorotate(Imagick $image)
{
    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);
}

The function might be used like this:

$img = new Imagick('/path/to/file');
autorotate($img);
$img->stripImage(); // if you want to get rid of all EXIF data
$img->writeImage();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNyxynyxView Question on Stackoverflow
Solution 1 - PhpdlemstraView Answer on Stackoverflow
Solution 2 - PhptarlebView Answer on Stackoverflow