Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP getimagesize() mixes up width and height

I use a PHP script that uploads an image, then gets the dimensions with PHP's getImageSize() and then does things to the image according to the pictures orientation (portrait or landscape).

However (PHP version 5.4.12) on some .jpg files it gets the height and width as they are, and in some (taken with an iPhone) it swaps them, thinking the portrait pictures are actually landscape.
It does not only happen on my local Wampserver, but also on a remote server (with a different PHP version).

Has anyone a clue how

1) to repair this or
2) find a way around the problem?

like image 892
Chiel Avatar asked Mar 27 '15 13:03

Chiel


1 Answers

Some cameras include an orientation tag within the metadata section of the file itself. This is so the device itself can show it in the correct orientation every time regardless of the picture's orientation in its raw data.

It seems like Windows doesn't support reading this orientation tag and instead just reads the pixel data and displays it as-is.

A solution would be to either change the orientation tag in afflicted pictures' metadata on a per-image basis, OR

Use PHP's exif_read_data() function to read the orientation and orient your image accordingly like so:

<?php
$image = imagecreatefromstring(file_get_contents($_FILES['image_upload']['tmp_name']));
$exif = exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty($exif['Orientation'])) {
    switch($exif['Orientation']) {
        case 8:
            $image = imagerotate($image,90,0);
            break;
        case 3:
            $image = imagerotate($image,180,0);
            break;
        case 6:
            $image = imagerotate($image,-90,0);
            break;
    }
}
// $image now contains a resource with the image oriented correctly
?>

References:

  • https://stackoverflow.com/a/10601175/1124793 (research as to why this is happening)
  • http://php.net/manual/en/function.exif-read-data.php#110894 (PHP Code)
like image 128
Pablo Canseco Avatar answered Oct 06 '22 18:10

Pablo Canseco