How to stop PHP iMagick auto-rotating images based on EXIF 'orientation' data

前端 未结 5 1428
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 23:52

Currently working with PHP and iMagick to develop a poster printing Web application.

This is the example image I am using to test upload/image editing features of th

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-03 00:05

    Good start -- a few additions to make the function more robust. First, case 3 occurs when the image appears upside down. There's a GREAT illustration of the different orientation codes by Calvin Hass. It's possible that orientation information may appear at a different part of the exif_read_data array (depending on camera model, I think), so I've tried to take that into account in my example code.

    Something like this:

    public function fixOrientation() {
    
        $exif = exif_read_data($this->imgSrc);
    
        if( isset($exif['Orientation']) )
            $orientation = $exif['Orientation'];
        elseif( isset($exif['IFD0']['Orientation']) )
            $orientation = $exif['IFD0']['Orientation'];
        else
            return false;
    
        switch($orientation) {
            case 3: // rotate 180 degrees
                $this->image->rotateimage("#FFF", 180);
            break;
    
            case 6: // rotate 90 degrees CW
                $this->image->rotateimage("#FFF", 90);
            break;
    
            case 8: // rotate 90 degrees CCW
                $this->image->rotateimage("#FFF", -90);
            break;
        }
    }
    

    The transformation & save leaves you without the previous EXIF information, including Orientation. The lack of Orientation in the transformed image will prevent further processing from attempting to 'correct' things by rotating again. I do wish Imagick had support for ImageMagick's -auto-orient, but oh well.

    Oh, also: the rotation is a lossy operation (unless you use jpegtran), so you should try to only do it in conjunction with a resize or other transformation.

提交回复
热议问题