PHP读取exif数据并调整方向

86

我正在使用以下代码来旋转上传的JPEG图像,如果方向不正确。 我只在上传自iPhone和Android的图像方面遇到问题。

if(move_uploaded_file($_FILES['photo']['tmp_name'], $upload_path . $newfilename)){
            chmod($upload_path . $newfilename, 0755);
            $exif = exif_read_data($upload_path . $newfilename);
            $ort = $exif['IFD0']['Orientation'];
            switch($ort)
            {

                case 3: // 180 rotate left
                    $image->imagerotate($upload_path . $newfilename, 180, -1);
                    break;


                case 6: // 90 rotate right
                    $image->imagerotate($upload_path . $newfilename, -90, -1);
                    break;

                case 8:    // 90 rotate left
                    $image->imagerotate($upload_path . $newfilename, 90, -1);
                    break;
            }
            imagejpeg($image, $upload_path . $newfilename, 100);
            $success_message = 'Photo Successfully Uploaded';
        }else{
            $error_count++;
            $error_message = 'Error: Upload Unsuccessful<br />Please Try Again';
        }

我从JPEG文件中读取EXIF数据的方式有问题吗?它没有像应该旋转图像。

当我运行var_dump($exif)时会发生什么:

array(41) {
    ["FileName"]=> string(36) "126e7c0efcac2b76b3320e6187d03cfd.JPG"
    ["FileDateTime"]=> int(1316545667)
    ["FileSize"]=> int(1312472)
    ["FileType"]=> int(2)
    ["MimeType"]=> string(10) "image/jpeg"
    ["SectionsFound"]=> string(30) "ANY_TAG, IFD0, THUMBNAIL, EXIF"
    ["COMPUTED"]=> array(8) {
        ["html"]=> string(26) "width="2048" height="1536""
        ["Height"]=> int(1536)
        ["Width"]=> int(2048)
        ["IsColor"]=> int(1)
        ["ByteOrderMotorola"]=> int(1)
        ["ApertureFNumber"]=> string(5) "f/2.8"
        ["Thumbnail.FileType"]=> int(2)
        ["Thumbnail.MimeType"]=> string(10) "image/jpeg" }
        ["Make"]=> string(5) "Apple"
        ["Model"]=> string(10) "iPhone 3GS"
        ["Orientation"]=> int(6)
        ["XResolution"]=> string(4) "72/1"
            ["YResolution"]=> string(4) "72/1" ["ResolutionUnit"]=> int(2) ["Software"]=> string(5) "4.3.5" ["DateTime"]=> string(19) "2011:09:16 21:18:46" ["YCbCrPositioning"]=> int(1) ["Exif_IFD_Pointer"]=> int(194) ["THUMBNAIL"]=> array(6) { ["Compression"]=> int(6) ["XResolution"]=> string(4) "72/1" ["YResolution"]=> string(4) "72/1" ["ResolutionUnit"]=> int(2) ["JPEGInterchangeFormat"]=> int(658) ["JPEGInterchangeFormatLength"]=> int(8231) } ["ExposureTime"]=> string(4) "1/15" ["FNumber"]=> string(4) "14/5" ["ExposureProgram"]=> int(2) ["ISOSpeedRatings"]=> int(200) ["ExifVersion"]=> string(4) "0221" ["DateTimeOriginal"]=> string(19) "2011:09:16 21:18:46" ["DateTimeDigitized"]=> string(19) "2011:09:16 21:18:46" ["ComponentsConfiguration"]=> string(4) "" ["ShutterSpeedValue"]=> string(8) "3711/949" ["ApertureValue"]=> string(9) "4281/1441" ["MeteringMode"]=> int(1) ["Flash"]=> int(32) ["FocalLength"]=> string(5) "77/20" ["SubjectLocation"]=> array(4) { [0]=> int(1023) [1]=> int(767) [2]=> int(614) [3]=> int(614) } ["FlashPixVersion"]=> string(4) "0100" ["ColorSpace"]=> int(1) ["ExifImageWidth"]=> int(2048) ["ExifImageLength"]=> int(1536) ["SensingMethod"]=> int(2) ["ExposureMode"]=> int(0) ["WhiteBalance"]=> int(0) ["SceneCaptureType"]=> int(0) ["Sharpness"]=> int(1) }

执行 var_dump($exif) 以查看 Android 手机产生的旋转数据。 - Marc B
我已经更新了帖子,包括$exif的var_dump。 - Jeff Thomas
1
好的,我清理了那里的垃圾。显然,方向字段不在'IFD0'部分中,它是$exif['COMPUTED']['Orientation'],并且值为6。 - Marc B
抱歉回复晚了。非常感谢您在这个问题上的帮助。在您的帮助和建议下,我已经解决了它。 - Jeff Thomas
1
$exif['Orientation']; 对我来说运行良好。与 $exif['some_section']['Orientation']; 相比,它可能是更好的选择。 - demosten
显示剩余8条评论
13个回答

85

基于Daniel的代码,我编写了一个函数,如果需要的话,它可以简单地旋转图像而不进行重采样。

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

一行版本(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;
        }
    }
}

你有关于WideImage的解决方案吗? - Yami Medina
在第一个版本(GD)中,当我调用这个函数时,应该传递什么给$&image? - Bharat Maheshwari
3
对于不理解如何从本地文件传递$&image参数的人,请按以下方式使用:$im = @imagecreatefromjpeg($local_filename); image_fix_orientation($im, $local_filename); 如果($im) { imagejpeg($im, $local_filename); imagedestroy($im); } - woheras
如果文件不是jpeg格式,这样做会更好。 - electrikmilk
2
对我来说,case 6case 8的旋转应该交换。也就是说,case 6 = -90case 8 = 90 - Tigger
显示剩余2条评论

64
imagerotate的文档中提到了与您使用的第一个参数类型不同的类型:
图像资源,由图像创建函数之一返回,例如imagecreatetruecolor()。
这是一个使用此函数的小例子:
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);
}

由于某种原因,由Android 4.1.2创建的图像不需要旋转,只需通过“imagecreatefromjpen()”加载图像,然后使用“imagejpeg()”将其保存回来。你知道为什么吗? - doron

48

对于上传图片的人来说,这是一个更简单的功能,它会在必要时自动旋转。

function image_fix_orientation($filename) {
    $exif = exif_read_data($filename);
    if (!empty($exif['Orientation'])) {
        $image = imagecreatefromjpeg($filename);
        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, $filename, 90);
    }
}

1
将此答案制作成一个简单的composer包,可以在github上找到(只有一个方法的类):https://github.com/diversen/image-auto-rotate - dennis
1
你使用了错误的角度值。在第6种情况下,你需要90度,在第8种情况下,你需要-90度。 - bernhardh
非常有用的函数,如果有人看到警告 Illegal IFD size,可以使用 @ operator 例如$exif = @exif_read_data($filename); - chebaby
@user462990 这个函数在本地图片上运行良好,但如何传递图片URL呢?我有一张存储在S3上的图片需要调整方向。 - ultrasamad

27
为什么没有人考虑镜像案例2、4、5、7?在exif方向领域中还有4个更多的案例: enter image description here 这里是一个针对文件名的完整解决方案:
function __image_orientate($source, $quality = 90, $destination = null)
{
    if ($destination === null) {
        $destination = $source;
    }
    $info = getimagesize($source);
    if ($info['mime'] === 'image/jpeg') {
        $exif = exif_read_data($source);
        if (!empty($exif['Orientation']) && in_array($exif['Orientation'], [2, 3, 4, 5, 6, 7, 8])) {
            $image = imagecreatefromjpeg($source);
            if (in_array($exif['Orientation'], [3, 4])) {
                $image = imagerotate($image, 180, 0);
            }
            if (in_array($exif['Orientation'], [5, 6])) {
                $image = imagerotate($image, -90, 0);
            }
            if (in_array($exif['Orientation'], [7, 8])) {
                $image = imagerotate($image, 90, 0);
            }
            if (in_array($exif['Orientation'], [2, 5, 7, 4])) {
                imageflip($image, IMG_FLIP_HORIZONTAL);
            }
            imagejpeg($image, $destination, $quality);
        }
    }
    return true;
}

优秀的解决方案。这是一个好点,因为许多用户上传镜像图像并且在最终图像上遇到问题。 - Herii
这个问题非常不对。"PHP团队"做了一半?这似乎是一个解决方案。 - UserOfStackOverFlow

9

以防万一有人看到这篇文章。根据我所了解的情况,上面的某些switch语句是错误的。

根据这里的信息,应该是:

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

它们确实是不正确的。我已经编辑过它们了,现在应该是正确的了。 - Firze
至少对我来说,第6个案例仍然是错误的。 - TEOL

6

值得一提的是,如果您正在使用命令行中的ImageMagick,您可以使用-auto-orient选项,该选项将根据现有的EXIF方向数据自动旋转图像。

convert -auto-orient /tmp/uploadedImage.jpg /save/to/path/image.jpg

请注意:如果在处理之前已经删除了EXIF数据,则该过程将无法按照描述的方式工作。

3

我不太想再提供另一组方向值,但根据我的经验,如果直接从iPhone上传竖向照片时使用上述任何值,最终都会得到颠倒的图像。以下是我最终采用的switch语句。

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

2

我在这里解释整个过程,我使用Laravel并使用Image Intervention包。

首先,我获取我的图像,并将其发送到另一个函数进行调整大小和其他功能,如果不需要此操作,则可以跳过...

在我的控制器中使用一个方法来获取文件。

 public  function getImageFile(Request $request){
    $image = $request->image;
    $this->imageUpload($image);
}

现在,我将其发送到调整大小并获取图像名称和扩展名...
public function  imageUpload($file){
    ini_set('memory_limit', '-1');
    $directory = 'uploads/';
    $name = str_replace([" ", "."], "_", $file->getClientOriginalName()) . "_";
    $file_name = $name . time() . rand(1111, 9999) . '.' . $file->getClientOriginalExtension();
    //path set
    $img_url = $directory.$file_name;
    list($width, $height) = getimagesize($file);
    $h = ($height/$width)*600;
    Image::make($file)->resize(600, $h)->save(public_path($img_url));
    $this->image_fix_orientation($file,$img_url);
    return $img_url;
}

现在我调用我的图像方向函数,
 public function image_fix_orientation($file,$img_url ) {
    $data = Image::make($file)->exif();
    if (!empty($data['Orientation'])) {
        $image = imagecreatefromjpeg($file);
        switch ($data['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, $img_url, 90);
    }

}

而这就是全部...

2

这是我基于 @user462990 的 PHP 7 函数:

/**
 * @param string $filePath
 *
 * @return resource|null
 */
function rotateImageByExifOrientation(string $filePath)
{
    $result = null;

    $exif = exif_read_data($filePath);
    if (!empty($exif['Orientation'])) {
        $image = imagecreatefromjpeg($filePath);
        if (is_resource($image)) {
            switch ($exif['Orientation']) {
                case 3:
                    $result = imagerotate($image, 180, 0);
                    break;

                case 6:
                    $result = imagerotate($image, -90, 0);
                    break;

                case 8:
                    $result = imagerotate($image, 90, 0);
                    break;
            }
        }
    }

    return $result;
}

使用方法:

    $rotatedFile = rotateImageByExifOrientation($absoluteFilePath);
    if (is_resource($rotatedFile)) {
        imagejpeg($rotatedFile, $absoluteFilePath, 100);
    }

1

我也使用了Intervention的orientate()函数,它完美地运行。

    $image_resize = Image::make($request->file('photo'));
    $image_resize->resize(1600, null,function ($constraint)
    {
        $constraint->aspectRatio();
    });
    $filename = $this->checkFilename();

    $image_resize->orientate()->save($this->photo_path.$filename,80);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接