img标记中的图像旋转不正确


Incorrect image rotation in img tag

我正在使用标准的php表单上传一些图像。

问题是,当我使用img标签显示一些图像时

<img src="http://www.example.com/image.jpg" alt="">

我得到了错误的旋转,有时图像是颠倒的,有时是45度旋转。

如果我通过访问直接在浏览器中加载图像

http://www.example.com/image.jpg

图片显示正确。

问题出在哪里?我该怎么解决?

我发现了问题。无法正常显示的图像是从三星和iPhone等移动设备上传的。所以EXIF的方向就是移动设备的方向。

要查看图像的确切外观,您可以在此处进行测试http://exif.regex.info/exif.cgi.即使你直接在Chrome或Firefox等浏览器中打开图像,你也会看到方向正确的图像,但如果你使用html img标签加载图像,它会显示exif方向。

因此,最好的解决方案是在上传图像之前检查exif的方向,然后使用php函数将其转换为正确的方向。

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');