Posts Tagged ‘image-rotation’

iphone image upload rotation php

Posted: April 4, 2014 in PHP
Tags:

When you browse mobile photos and upload it to server using php then many times you can face orientation issue. i.e. image rotates by 90 angle. Below PHP code will handle that.


// Input: $filePath : path to image file
// Output: If there is any orientation required then function will change that image accordingly
function setDeviceRotation($filePath)
{
$exif = exif_read_data($filePath);

//if there is orientation change
$exif_orient = isset($exif['Orientation']) ? $exif['Orientation'] : 0;
$rotateImage = 0;

//convert exif rotation to angles
if (6 == $exif_orient)
{
$rotateImage = 90;
$imageOrientation = 1;
}
elseif (3 == $exif_orient)
{
$rotateImage = 180;
$imageOrientation = 1;
}
elseif (8 == $exif_orient)
{
$rotateImage = 270;
$imageOrientation = 1;
}
//if the image is rotated
if ($rotateImage)
{
$rotateImage = -$rotateImage;
$info   = getimagesize($filePath);
$fileType = $info[2];
switch ($fileType)
{
case '2': //image/jpeg
$source = imagecreatefromjpeg($filePath);
$rotate = imagerotate($source, $rotateImage, 0);
imagejpeg($rotate,$filePath);
break;
case '3': //image/png
$source = imagecreatefrompng($filePath);
$rotate = imagerotate($source, $rotateImage, 0);
imagepng($rotate,$filePath);
break;
case '1':
$source = imagecreatefromgif($filePath);
$rotate = imagerotate($source, $rotateImage, 0);
imagegif($rotate,$filePath);
break;
default:
break;
}
}
// The image orientation is fixed, pass it back for further processing
return $file;
}

Advertisements