Change photo extensions by content


Recently I had an interesting problem.  I had a lot of files in a directory, all photos, with their filenames messed up, especially their extensions.  So, in order to clear them and keep only the good ones, I had first to rename them in a more consistent manner (the JPEG photos ending with .jpeg, the PNGs with .png and so on).

I guess there is probably a plethora of appropriate tools, but I had no time to search in the chaotic internet, so I wrote a small PHP script (with a little help from the shell: command ‘file‘) and run it from the command line.

The script just parses the output of the file command and renames each file accordingly.

I’m putting this here, just in case it will be useful to someone else also:


$res = array();
exec( "file *", $res);

foreach( $res as $f) {
list( $fn, $ft) = split( ':', $f);
if (strpos( $ft, "JPEG") !== false) {
rename( $fn, $fn .".jpeg");
} else if (strpos( $ft, "PNG") !== false) {
rename( $fn, $fn .".png");
} else
echo "cannot rename $fnn";

I’m actually testing only for JPEG & PNG files since I know that I have only these two types.
Don’t forget to make this file executable if you want to run it from the command line.

Visit The Light of the LAMP blog for more…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.