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;
}
}
}