Skip to content

Instantly share code, notes, and snippets.

@cowboymathu
Last active March 26, 2019 20:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cowboymathu/a84c513213dd119d347e to your computer and use it in GitHub Desktop.
Save cowboymathu/a84c513213dd119d347e to your computer and use it in GitHub Desktop.
Rotate archived images to correct orientation
<?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);
}
?>
@RP92
Copy link

RP92 commented Mar 26, 2019

Great pity code I can't work with .jpeg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment