Last active
March 26, 2019 20:31
-
-
Save cowboymathu/a84c513213dd119d347e to your computer and use it in GitHub Desktop.
Rotate archived images to correct orientation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Correct image orientation v1.0 | |
Author: Mathuvathanan Mounasamy | |
Licensed under the MIT license | |
This funtion 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) { | |
$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); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great pity code I can't work with .jpeg