PHP getimagesize()混合了宽度和高度


PHP getimagesize() mixes up width and height

我使用一个PHP脚本上传图像,然后用PHP的getImageSize()获取尺寸,然后根据图片的方向(纵向或横向)对图像进行处理。

然而(PHP版本5.4.12)在一些.jpg文件上,它会得到它们的高度和宽度,而在一些(用iPhone拍摄)中,它会交换它们,认为肖像图片实际上是横向的
它不仅发生在我的本地Wampserver上,也发生在远程服务器上(使用不同的PHP版本)。

有人知道

1) 修复此或
2) 想办法解决这个问题吗?

有些相机在文件本身的元数据部分包含一个方向标记。这样,无论图片在原始数据中的方向如何,设备本身每次都可以以正确的方向显示。

Windows似乎不支持读取此方向标记,而只是读取像素数据并按原样显示。

一种解决方案是在每张图像的基础上更改受影响图片元数据中的方向标签,或者

使用PHP的exif_read_data()函数读取方向并相应地调整图像的方向,如下所示:

<?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
?>

参考文献:

  • https://stackoverflow.com/a/10601175/1124793(研究为什么会发生这种情况)
  • http://php.net/manual/en/function.exif-read-data.php#110894(PHP代码)

函数getimagesize()更改横向(水平)照片中的宽度和高度。你可以使用这个代码:

<?php
$img = "test.jpg";
$exif = exif_read_data($img);
if(empty($exif['Orientation'])) {
    list($width, $height, $type, $attr) = getimagesize($img);
}else{
    list($height, $width, $type, $attr) = getimagesize($img);
}
?>

但它在PHP7及以上版本中被自动修复。