PHP read_exif_data and Adjust Orientation
The documentation for imagerotate refers to a different type for the first parameter than you use:
An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().
Here is a small example for using this function:
function resample($jpgFile, $thumbFile, $width, $orientation) {
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($jpgFile);
$height = (int) (($width / $width_orig) * $height_orig);
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($jpgFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Fix Orientation
switch($orientation) {
case 3:
$image_p = imagerotate($image_p, 180, 0);
break;
case 6:
$image_p = imagerotate($image_p, 90, 0);
break;
case 8:
$image_p = imagerotate($image_p, -90, 0);
break;
}
// Output
imagejpeg($image_p, $thumbFile, 90);
}
Based on Daniel's code I wrote a function that simply rotates an image if necessary, without resampling.
GD
function image_fix_orientation(&$image, $filename) {
$exif = exif_read_data($filename);
if (!empty($exif['Orientation'])) {
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;
}
}
}
One line version (GD)
function image_fix_orientation(&$image, $filename) {
$image = imagerotate($image, array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($filename)['Orientation'] ?: 0], 0);
}
ImageMagick
function image_fix_orientation($image) {
if (method_exists($image, 'getImageProperty')) {
$orientation = $image->getImageProperty('exif:Orientation');
} else {
$filename = $image->getImageFilename();
if (empty($filename)) {
$filename = 'data://image/jpeg;base64,' . base64_encode($image->getImageBlob());
}
$exif = exif_read_data($filename);
$orientation = isset($exif['Orientation']) ? $exif['Orientation'] : null;
}
if (!empty($orientation)) {
switch ($orientation) {
case 3:
$image->rotateImage('#000000', 180);
break;
case 6:
$image->rotateImage('#000000', 90);
break;
case 8:
$image->rotateImage('#000000', -90);
break;
}
}
}