Working with Apple's iOS image orientation

Using PHP and ImageMagick

You might notice pictures taken with an iOS device (iPhone or iPad) look like they are not rotated properly when transferring them to another device or software. This happens because the device is held at a certain angle when the picture is taken and it’s up to the software at the receiving end to display it however it wants.

Apple’s camera will write orientation info into the exif headers of images taken and you can rotate it accordingly.

Here is an example of rotating an image using PHP with the ImageMagick library;

<?php

// Rotate iOS image
// @author Richard Sumilang <me@richardsumilang.com>

$imageFile = '/foo/bar.jpg';
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $imageFile);
finfo_close($finfo);

// Detect if jpeg or tiff
if ( in_array($mimeType, ['image/jpeg', 'image/tiff']) ) {
    $exif = exif_read_data($imageFile);
    if ( isset($exif['Orientation']) && !empty($exif['Orientation']) ) {

        // Decide orientation
        if ( $exif['Orientation'] == 3 ) {
            $rotation = 180;
        } else if ( $exif['Orientation'] == 6 ) {
            $rotation = 90;
        } else if ( $exif['Orientation'] == 8 ) {
            $rotation = -90;
        } else {
            $rotation = 0;
        }

        // Rotate the image
        if ( $rotation ) {
            $imagick = new Imagick();
            $imagick->readImage($imageFile);
            $imagick->rotateImage(new ImagickPixel('none'), $rotation);
            $imagick->writeImage($imageFile);
            $imagick->clear();
            $imagick->destroy();
        }

    }
}

Note: Only jpeg and tiff files contain exif information.

Oct 17, 2014 Programming

Support this blog

Buy yourself ANYTHING!

That's right! Shop as you normally would using Amazon.com with my affiliate link and the commissions made go directly into keeping this blog healthy. It's that simple! The hardware and software costs used for this site comes out of my own pocket and it's expensive. Lets keep this site ad free :)

Start shopping on Amazon.com now!

Thank you!
Richard S.