The Pug Automatic

AppleScript Folder Action to add missing image extensions on download

Written November 21, 2008. Tagged OS X, AppleScript.

My girlfriend saves a lot of pictures off the web, daily.

She uses the Easy DragToGo Firefox extension so she can just drag the image to save it to ~/Downloads. She has a stack of that folder in the dock, so she can immediately see that it saved successfully.

But sometimes, an image will have an incorrect extension ("foo.php") or no extension ("foo"), and OS X will not show the thumbnail in the stack or in Finder, and won't know how to open the file.

Renaming manually is a bother, especially when you don't know what file type it's supposed to be. So I made an AppleScript Folder Action that does this automatically.

When a new file appears in the folder, by being saved or moved there, the script uses the file command to get the file type (try man file for more info on how that works). Then, if the file type is JPG, PNG or GIF, and the filename extension does not match that file type, the correct extension is added.

The script is here:

on adding folder items to myFolder after receiving myFiles
repeat with myFile in myFiles
set myPath to (POSIX path of myFile)
set myType to do shell script "file --mime-type -br " & (quoted form of myPath)
if myType is "image/jpeg" and myPath does not end with ".jpg" and myPath does not end with ".jpeg" then
set newExtension to ".jpg"
else if myType is "image/gif" and myPath does not end with ".gif" then
set newExtension to ".gif"
else if myType is "image/png" and myPath does not end with ".png" then
set newExtension to ".png"
else
set newExtension to null
end if
tell application "Finder"
if newExtension is not null then
set name of myFile to (name of myFile) & newExtension
end if
end tell
end repeat
end adding folder items to