Monday, November 14, 2016

PHP- function to correct all the images orientation in a given path or directory

<?php
/*
This function correct all the images orientation in a given path or directory.

Run:    php -r "require 'correctImageOrientation.php'; correctImageOrientation('test/');"
        or
        php -r "require 'correctImageOrientation.php'; correctImageOrientation('test/test1');"
        or
        php -r "require 'correctImageOrientation.php'; correctImageOrientation('test');"
*/
function correctImageOrientation($directory) {
   
    ini_set('memory_limit','2048M');
   
    $scanned_directory = array_diff(scandir($directory), array('..', '.'));
    echo "<pre>";
    print_r("scanned directory: \r\n");
    print_r($scanned_directory);
    echo "</pre>\r\n";
    foreach ($scanned_directory as &$file) {

        if (is_dir($directory."/".$file)) {
            correctImageOrientation($directory."/".$file);
        } else {                                   
            $filen = explode(".", $file);
            $ext = end($filen);
            try {

                $exif = @exif_read_data($directory."/".$file);

                $orientation = $exif['Orientation'];

                if (isset($orientation) && $orientation != 1){
                    switch ($orientation) {
                        case 3:
                        $deg = 180;
                        break;
                        case 6:
                        $deg = 270;
                        break;
                        case 8:
                        $deg = 90;
                        break;
                    }

                    if ($deg) {

                        // If png
                        if ($ext == "png") {
                            $img_new = imagecreatefrompng($directory."/".$file);
                            $img_new = imagerotate($img_new, $deg, 0);

                            // Save rotated image
                            imagepng($img_new,$directory.$file);
                        }else {
                            $img_new = imagecreatefromjpeg($directory."/".$file);
                            $img_new = imagerotate($img_new, $deg, 0);

                            // Save rotated image
                            imagejpeg($img_new,$directory."/".$file,80);
                        }
                    }
                    echo "<pre>";
                    print_r("image changed: \r\n");
                    print_r($directory."/".$file);
                    echo "</pre>\r\n";
                }

            } catch (Exception $e) {
                echo "error:";
                echo $e;
                echo "error";
            }
        }
    }
    unset($file);
}


correctImageOrientation('test/test1') ;
?>

1 comment: