How to fix unexpectedly rotating image file on WordPress?

blog
Reading Time: < 1 minutes



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
Contributetokurofuku/wordpress-containerdevelopmentbycreatinganaccountonGitHub.



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

Image Rotation Repair
TheImageRotationRepairpluginsimplyfixesimageorientationbasedonEXIFdata.Thisisprimarilyapatchformis-orientedimagesdeliveredfrom…

Conclusion

How was it?

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

Author

I am Japanese software engineer having over 15 years career in embedded system software.
I have worked for designing/quality assurance products which has embedded linux.
I love Raspberry Pi.
I am also interested in stock market.
I married Hong Konger as international marriage.

Please follow me
blogPHPWordpress
Please follow me
The World's Linux Journal

Comments

タイトルとURLをコピーしました