Reputation: 1073
I am uploading some images by using a standard php form.
The problem is that when i show some images by using the img tag
<img src="http://www.example.com/image.jpg" alt="">
i get the wrong rotation, sometimes the images are upside down, sometimes are 45 degrees rotated.
If i load the image directly in browser by accessing
http://www.example.com/image.jpg
the image shows right.
What seems to be the problem and how can i fix this ?
Upvotes: 2
Views: 6958
Reputation: 1073
I found the problem. The images that don't show properly are uploaded from mobile devices such as Samsung and iPhone. So the EXIF orientation is that of the mobile.
To see the exact exif of the image, you can test it here http://exif.regex.info/exif.cgi. Even if you open the image directly in browsers such as Chrome or Firefox, you will see the image with the right orientation, but if you load the image using the html img tag, it will show the exif orientation.
So the best solution is to check exif orientation before uploading image, and then convert it to the right orientation by using a php function.
function image_fix_orientation($path)
{
$image = imagecreatefromjpeg($path);
$exif = exif_read_data($path);
if (empty($exif['Orientation']))
{
return false;
}
switch ($exif['Orientation'])
{
case 3:
$image = imagerotate($image, 180, 0);
break;
case 6:
$image = imagerotate($image, - 90, 0);
break;
case 8:
$image = imagerotate($image, 90, 0);
break;
}
imagejpeg($image, $path);
return true;
}
// For JPEG image only
image_fix_orientation('/path/to/image.jpg');
Upvotes: 3