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

前端 未结 5 1423
伪装坚强ぢ
伪装坚强ぢ 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:11

    "However - iMagick, when __construct'ed with this image, automatically rotates it an additional 90 degrees CCW as per [Orientation] => 6 (I think!)."

    The problem is actually the opposite of that. Imagick doesn't auto rotate the image. You're only seeing it correctly in other software / your web browser because those programs do auto rotate it based on the EXIF info. Certain operations in Imagick will cause you to lose that correct EXIF info (copying the image, thumbnailImage(), stripImage(), and other manipulations). So what you need to do in that case is actually physically rotate the image.

    The answer from ajmicek is good, but it could be improved a bit by using Imagick's own built in functions rather than the PHP EXIF functions. Also that snippet seems to have been a part of a class, so it can't be used as a separate function as-is. It's also a good idea to set the correct EXIF orientation with setImageOrientation() after you rotate it.

    // Note: $image is an Imagick object, not a filename! See example use below.
    function autoRotateImage($image) {
        $orientation = $image->getImageOrientation();
    
        switch($orientation) {
            case imagick::ORIENTATION_BOTTOMRIGHT: 
                $image->rotateimage("#000", 180); // rotate 180 degrees
                break;
    
            case imagick::ORIENTATION_RIGHTTOP:
                $image->rotateimage("#000", 90); // rotate 90 degrees CW
                break;
    
            case imagick::ORIENTATION_LEFTBOTTOM: 
                $image->rotateimage("#000", -90); // rotate 90 degrees CCW
                break;
        }
    
        // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image!
        $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
    }
    

    Example use:

    $image = new Imagick('my-image-file.jpg');
    autoRotateImage($image);
    // - Do other stuff to the image here -
    $image->writeImage('result-image.jpg');
    

提交回复
热议问题