Monday, March 2, 2009 - 12:36
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function sequentialImages($path, $sort=false) { $i = 1; $files = glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT); if ( $sort !== false ) { usort($files, $sort); } $count = count($files); foreach ( $files as $file ) { $newname = str_pad($i, strlen($count)+1, '0', STR_PAD_LEFT); $ext = substr(strrchr($file, '.'), 1); $newname = $path.'/'.$newname.'.'.$ext; if ( $file != $newname ) { rename($file, $newname); } $i++; } } |
The following function can be used in the second parameter to sort the files by their last modified time.
1 2 3 4 5 6 7 8 | function sort_by_mtime($file1, $file2) { $time1 = filemtime($file1); $time2 = filemtime($file2); if ( $time1 == $time2 ) { return 0; } return ($time1 < $time2) ? 1 : -1; } |
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 2 3 4 5 | file1.gif file2.gif wibble.gif wobble.gif 02.gif |
And renames them to the following:
1 2 3 4 5 | 01.gif 02.gif 03.gif 04.gif 05.gif |
Category:
Comments
Submitted by Jamie Bicknell (not verified) on Wed, 03/04/2009 - 18:15 Permalink
Add new comment