Monday, 13 August 2018

Sequentially Rename All Image Files In A Directory With PHP

The following function will rename all of the image files in a directory to be sequential. The parameters are the path of the directory that the files are in and the name of a function that will be used to sort the array of files through the PHP usort() function.
  1. function sequentialImages($path, $sort=false) {
  2. $i = 1;
  3. $files = glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT);
  4.  
  5. if ( $sort !== false ) {
  6. usort($files, $sort);
  7. }
  8.  
  9. $count = count($files);
  10. foreach ( $files as $file ) {
  11. $newname = str_pad($i, strlen($count)+1, '0', STR_PAD_LEFT);
  12. $ext = substr(strrchr($file, '.'), 1);
  13. $newname = $path.'/'.$newname.'.'.$ext;
  14. if ( $file != $newname ) {
  15. rename($file, $newname);
  16. }
  17. $i++;
  18. }
  19. }
The following function can be used in the second parameter to sort the files by their last modified time.
  1. function sort_by_mtime($file1, $file2) {
  2. $time1 = filemtime($file1);
  3. $time2 = filemtime($file2);
  4. if ( $time1 == $time2 ) {
  5. return 0;
  6. }
  7. return ($time1 < $time2) ? 1 : -1;
  8. }
Putting these two function together we can call the sequentialImages() function like this.
sequentialImages('files','sort_by_mtime');
This function takes the following set of images:
  1. file1.gif
  2. file2.gif
  3. wibble.gif
  4. wobble.gif
  5. 02.gif
And renames them to the following:
  1. 01.gif
  2. 02.gif
  3. 03.gif
  4. 04.gif
  5. 05.gif

0 comments:

Post a Comment