user3541125 user3541125 - 4 months ago 25
AppleScript Question

Extracting frames from GIF

I am trying to use Applescript or Terminal (or terminal via applescript using the do shell script command) to automatically extract the frames from a selected .gif file. I know how to do the click and drag method using Preview.app, but is there a way to do this automatically?

Thanks!
Eric

Answer

You can use the AppKit framework to extract frames from GIF.

Here is the AppleScript (Tested on Mavericks):

set gifFiles to choose file of type "com.compuserve.gif" with prompt "Select GIF's files" with multiple selections allowed
set dest to quoted form of POSIX path of (choose folder with prompt "Select the folder to save gif's frames")

set pScript to quoted form of "from AppKit import NSApplication, NSImage, NSImageCurrentFrame, NSGIFFileType; import sys, os
tName=os.path.basename(sys.argv[1])
dir=sys.argv[2]
app=NSApplication.sharedApplication() 
img=NSImage.alloc().initWithContentsOfFile_(sys.argv[1])
if img:
     gifRep=img.representations()[0]
     frames=gifRep.valueForProperty_('NSImageFrameCount')
     if frames:
         for i in range(frames.intValue()):
             gifRep.setProperty_withValue_(NSImageCurrentFrame, i)
             gifRep.representationUsingType_properties_(NSGIFFileType, None).writeToFile_atomically_(dir + tName + ' ' + str(i + 1).zfill(2) + '.gif', True)
         print (i + 1)"

repeat with f in gifFiles
    set numberOfExtractedGIFs to (do shell script "/usr/bin/python -c " & pScript & " " & (quoted form of POSIX path of f) & " " & dest) as integer
end repeat

This script show two dialog window, a dialog to choose GIF files, a dialog to choose the destination folder.