How to fix unexpectedly rotating image file on WordPress?

blog
Reading Time: < 1 minute



Recently my uploaded image files are rotated unexpectedly.

Then I fixed by referring this web site.
– Japanese geek

The point is to use EXIF information in image file.

[WordPress] スマホで縦向き撮影した写真が勝手に横向く(回転する)問題 | IT女子のお気に入りフォルダ
スマホで縦向きに撮影した写真(JPEG画像)をWordPressにアップロードしたら、勝手に回転して横向きにな



This is source code added in functions.php.
Point is from switch ($orientation) parts.
– I just referred above site sample…

function rotate_uploaded_image_file($file) {
    if ($file['type'] == 'image/jpeg') {
        $image = wp_get_image_editor($file['file']);
        if (!is_wp_error($image)) {
            $exif = exif_read_data($file['file']);
            $orientation = $exif['Orientation'];
            if (!empty($orientation)) {
                switch ($orientation) {
                    case 8:  
                        $image->rotate(90);
                        break;  
                    case 3:
                        $image->rotate(180);
                        break;
                    case 6:
                        $image->rotate(-90);
                        break;
                }   
            }
            $image->save($file['file']);
        }
    }
    return $file;
}
add_action('wp_handle_upload', 'rotate_uploaded_image_file');



FYI
This is official API guide of PHP.

PHP: exif_read_data - Manual



And we need exif extension to use exif_read_data().
Please visit my git commit for more detail.

Added exif extension for correct orientation of image file. · kurofuku/wordpress-container@eae9ddf
Contribute to kurofuku/wordpress-container development by creating an account on GitHub.



In some internet site there is plugin to resolve this problem.
But in my environment it didn’t resolve. 

Image Rotation Repair
The Image Rotation Repair plugin simply fixes image orientation based on EXIF data. This is primarily a patch for mis-or...

Conclusion

How was it?

I got bored to fix rotating manually, so I automated! 

Comments

Copied title and URL