Skip to content

Instantly share code, notes, and snippets.

@MarcosBL
Created August 13, 2013 01:10
Show Gist options
  • Save MarcosBL/6216924 to your computer and use it in GitHub Desktop.
Save MarcosBL/6216924 to your computer and use it in GitHub Desktop.
Sorting Images based on Exif data
<?php
$filetypes = array('jpg','jpeg','png','gif','bmp','tiff');
$source = './images_unsorted';
$target = './images_sorted';
$iterator = new RecursiveDirectoryIterator($source);
$bytestotal = 0;
$nbfiles = 0;
foreach (new RecursiveIteratorIterator($iterator) as $filename=>$fileobj) {
$basename = $fileobj->getBasename();
$extension = strtolower(substr($basename, strrpos($basename, '.')+1));
if (in_array($extension, $filetypes)) {
// read creation date from exif information, otherwise mtime
echo $filename."\n";
$exif = exif_read_data($filename, 'IFDO', 0);
if ($exif!==false && isset($exif['DateTime'])) {
$edate = $exif['DateTime'];
$ts = strtotime($edate);
} else {
$ts = filemtime($filename);
}
// target folder
$datestr = date('Y', $ts).'-'.date('m', $ts);
$targetfolder = $target.'/'.$datestr;
if (!file_exists($targetfolder)) {
mkdir($targetfolder);
}
// copy file
$targetfile = $targetfolder.'/'.$basename;
if (!file_exists($targetfile)) {
copy($filename, $targetfile);
} else {
echo "$targetfile exists!\n";
}
}
}
$bytestotal=number_format($bytestotal);
echo "Total: $nbfiles files, $bytestotal bytes\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment