Image getting rotated automatically on upload

detj picture detj · Mar 14, 2011 · Viewed 20.4k times · Source

I'm trying to upload a base64 encoded image and save after decoding it. Image is getting uploaded and saved, and I can access it using a URL and everything..but the image gets rotated by 90 degrees anti-clockwise and I have no idea WHY!!

The place where I get the encoded data is fine, as putting it in <img /> works fine!

function saveImageData($base64Data) {
    $base64_decoded = base64_decode($base64Data);
    $im = imagecreatefromstring($base64_decoded);
    if ($im !== false) {
        $imagepath = '/public/uploads/' . time() . '.jpg';
        imagejpeg($im, $imagepath);
        chmod($imagepath, 0755);
        imagedestroy($im);
    } else {
        return false;
    }
    return $imagepath;
}

I'm not using any rotation functions, but still its getting rotated. I can use a PHP GD function like imagerotate, but don't want to for reasons like black backgrounds etc.

If you can help..you r the awesomest person!!

Answer

Matt Gibson picture Matt Gibson · Mar 14, 2011

My guess would be that the image you're uploading is actually rotated, but is being corrected because it contains rotation data in its EXIF section. (For example, a camera may be aware of portrait orientation when taking a photo, and save that information in the EXIF data; some viewing software is aware of the rotation data and will auto-rotate the photo when viewing it.) In which case, the image might just be appearing to be rotated for you, depending on what you're using to view it.

Are you viewing the "before upload" and "after upload" images using the same software? What happens if you look at them both using the same web browser, say?

What happens if you try a different image, preferably from a different source? Do you have any software that will allow you to view the image's EXIF data? Look for the "Orientation" value; anything other than "1" means there's a rotation set for the image (see this page for a decent description.)

So, in summary, I'd say that that the underlying image in the JPEG file is at the "wrong" orientation, and the EXIF data contains information to correct that rotation for display. This is very likely if the source is, for example, an iPhone, which having just played with mine, seems to store its underlying image data in landscape orientation, but set the EXIF data if the image was actually taken (and should therefore be displayed) as portrait.

Best way to fix it is almost certainly to examine the EXIF data on the file after upload, using the PHP EXIF functions and rotate the image as necessary to correct the orientation before saving your own copy.