Extracting frames from GIF - macos

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

ImageMagick gives you a cmdlet that lets extract frames of an animated gif.
This will extract the first 10 frames of the file "animated.gif"
# convert 'animated.gif[0-10]' frames%03d.png

For anyone interested in the way to export a single frame with the native Preview app...
Open the GIF with OS X native Preview app
Scroll to the frame you want to extract
Click and drag the icon (in the left pane) to your desktop
http://www.macobserver.com/tmo/article/preview-extracting-frames-from-animated-gifs

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.

Related

AppleScript Droplet to Convert PSD and TIF to JPG

There are a lot of examples of converters to JPG and i am trying to change one for my needs but i need little help please.
The requirements are:
It should be an AppleScript Droplet. I am using Script Editor ( for some reason Automator can't run a simple droplet drag and drop function for me ).
The output folder for the JPGs should not be prompted by the user .. but set as a variable in the code permanently and easly changed.
The quality ( compression ) of the converted JPG should also have to be easly customisable in the code.
The converted JPG files have to be converted to Color profile Adobe RGB 1998 if necessary.
I know Image Events allow us to set the JPG compression like :
save openedFile as JPEG with compression level (low|medium|high)
but unfortunately i need more customisation.
A shell script will help me to set the level from 10 to 100 but unfortunately i can't implement the shell script properly.
Little help please about points 3 and 4.
Thank you !
on run
display dialog "Please drag image files to this script to turn them into JPEGs"
end run
on open draggeditems
set End_Folder to "Macintosh HD:Users:zzz:Desktop:End"
repeat with currentFile in draggeditems
tell application "Image Events"
set openedFile to open (currentFile as alias)
set fileLocation to the location of openedFile
set fileName to the name of openedFile
set Path_to_Converted_File to (End_Folder & ":" & text 1 thru -5 of fileName & ".jpg")
do shell script "sips --setProperty formatOptions 10 " & openedFile
save openedFile as JPEG in Path_to_Converted_File
--save openedFile as JPEG with compression level low in Path_to_Converted_File (low|medium|high)
close openedFile
end tell
end repeat
end open
Mixing up Image Events and sips is more confusing than useful, and since sips can perform the various options you are looking for (such as 3 & 4), it makes more sense to use it for everything. Setting a few variables for the various options will let you change them as needed, or if adding preferences or whatever. The sips man page will give you more details about the various options; I’ve added comments for the ones used in the following script:
on run
open (choose file with prompt "Select image files to turn into JPEGs:" with multiple selections allowed)
end run
on open draggeditems
set destination to (((path to desktop folder) as text) & "End:") -- folder path (trailing delimiter)
set format to "jpeg" -- jpeg | tiff | png | gif | jp2 | pict | bmp | qtif | psd | sgi | tga
set extension to ".jpg" -- extension to match format
set compression to 10 -- low | normal | high | best | <percent>
set profile to quoted form of "/System/Library/ColorSync/Profiles/AdobeRGB1998.icc" -- POSIX path to color profile
repeat with thisFile in draggeditems
set theName to justTheName for thisFile
set originalFile to quoted form of POSIX path of thisFile
set convertedFile to quoted form of POSIX path of (destination & theName & extension)
do shell script "sips -s format " & format & " -s formatOptions " & compression & " -m " & profile & space & originalFile & " --out " & convertedFile
end repeat
end open
on justTheName for filePath
tell application "System Events" to tell disk item (filePath as text)
set {fileName, extension} to {name, name extension}
end tell
if extension is not "" then set fileName to text 1 thru -((count extension) + 2) of fileName -- just the name part
return fileName
end justTheName
Edited to add:
The shell script is expecting POSIX paths, so the aliases passed to the open handler are coerced and quoted in the event they contain spaces.
There is a lot wrong in your script. It is not clear why you are opening the file for writing before sending it to a shell command. sips does not operate on open FILE references. sips will need to open the file from a POSIX path. I think this may do what you want (you will need to implement error checking, etc.):
on open draggeditems
set End_Folder to "~/Desktop/End/"
repeat with currentFile in draggeditems
do shell script "sips --setProperty formatOptions 10 " & quoted form of POSIX path of currentFile & " --out " & End_Folder
end repeat
end open

How to change filename before duplicating Applescript

Currently I have a Applescript that does the following:
Copy a file from a certain directory to the current opened finder window.
Open a dialog box to rename this file.
However, it would be nicer if the dialog box to specify a name pops up before the moving takes place, so the original file is not copied first and then renamed. Could anyone help me how to achieve this?
property y : POSIX file "/Users/thijmendam/Documents/Newfile/Naamloos.txt" as alias
tell application "Finder"
set x to target of window 1 as alias
duplicate y to x
set name of file "Naamloos.txt" of folder x to the text returned of (display dialog "Rename" default answer "")
end tell
This should do it:
property y : POSIX file "/Users/thijmendam/Documents/Newfile/Naamloos.txt" as alias
tell application "Finder"
set x to target of window 1 as alias
set newFileName to text returned of (display dialog "Rename" default answer "")
set name of (duplicate y to x with replacing) to newFileName
end tell
I added with replacing to prevent an error being thrown if a file of that name already exists. You can remove this or just add a try...on error...end try error-catching block to cater for this situation.
The Terminal command cp can also be used to copy files from the command line. This will copy the file myfile.ext from the Desktop to the Documents folder without renaming it:
cp ~/Desktop/myfile.ext ~/Documents/
This will copy and rename the file in one go:
cp ~/Desktop/myfile.ext ~/Documents/renamed.ext
Note that cp will overwrite existing files without warning.
You can execute Terminal commands directly from within AppleScript using do shell script.
Implementing this with the AppleScript above could be done like this:
property y : POSIX file "/Users/CK/Desktop/syringet.jpg" as alias
tell application "Finder"
set x to POSIX path of (target of front window as alias)
set newFileName to text returned of (display dialog "Rename" default answer "")
set y to POSIX path of y
end tell
set command to "cp " & quoted form of y & " " & quoted form of ([x, newFileName] as text)
do shell script command
On a final note, if you didn't want to have to specify the file's extension in the dialog box (as it's unlikely you'll need to change that), you can make use of the name extension property. In the case of Naamloos.txt, the value of this property will be "txt".
Amend the scripts to reflect this implementation:
set name of (duplicate y to x with replacing) to newFileName & "." & name extension of y
in the first instance, or:
...
set [ext, y] to [name extension, POSIX path] of y
end tell
set command to "cp " & quoted form of y & " " & quoted form of ([x, newFileName, ".", ext] as text)

Retina display: How to display images in native pixel resolution in Finder and Preview

This is a pseudo question to share my own trick and script below.
The point is to be able to display image pixel for pixel on Retina displays. This is mainly useful for high resolution image and/or for developers working on HDPI version of images.
The solution works well only if the display setting is set to 2:1 ratio in the OS X preferences. Beware, late 2016 MacBook Pro default setting is not set to 2:1 by default. You should set it on the medium setting to get it right.
Finder : the simple trick is to give a name ending with #2x (before the extension): my_image#2x.jpg . Then when using Quick Look feature the image is pixel-wise. As this naming scheme is recommended for retina images, both normal and HDPI images display at same size, as expected, the retina being sharper.
Preview : In preview, the DPI resolution of an image is interpreted as normal if it is set to 72dpi. By setting it to 144, you get the right display ratio. One can achieve the same effect at 72dpi by changing the display scale to 50%, but the scale setting does not stick to the image file while the DPI setting does. Change it through the Tools->Size menu item.
Here below is a small applescript to automate 144dpi setting from the Finder.
tell application "Finder"
repeat with item_cour in selection as list
if word 1 of (the kind of item_cour as text) is "Image" then
set path_cour to POSIX path of (item_cour as text)
do shell script "p_cour='" & path_cour & "';
tags=$(xattr -px com.apple.metadata:_kMDItemUserTags \"$p_cour\");
f_info=$(xattr -px com.apple.FinderInfo \"$p_cour\");
sips -s dpiHeight 144 -s dpiWidth 144 \"$p_cour\";
xattr -wx com.apple.FinderInfo '$f_info' \"$p_cour\";
xattr -wx com.apple.metadata:_kMDItemUserTags \"$tags\" \"$p_cour\" "
-- do shell script "convert \"" & path_cour & "\" -set units PixelsPerInch -density 144 \"" & path_cour & "\""
end if
end repeat
end tell
Since the sips command does not preserve tags, the script includes 4 lines to get and set them back to the file after it has been modified, using the xattr command.
To install the script: open the script editor, create a new document, paste the code and save it into the ~/Library/Scripts/Finder folder.
Be sure to check the Show the Script Menu option in Script editor preference.
To use the script: select image file(s) in Finder and activate the script from the menu.

Resize images to specific width only (AppleScript or Automator)

I've been searching google.com a couple of hours trying to find a way to do this, but there is no answer. Everywhere is resize to the longest size, but nothing about resize to the specified width only.
Is there any way in Automator or AppleScript to resize images to a specified width only, instead of just the longest size? I need my output images to be a specific width ony (e.g 200px).
You can do this with plain AppleScript and a shell utility entitled sips:
on open droppings
repeat with everyDrop in droppings
set originalFile to quoted form of POSIX path of (everyDrop as text)
tell application "Finder"
set originalName to everyDrop's name
set imageContainer to (everyDrop's container as text)
end tell
set reSizedName to "200W" & originalName
set outputPath to quoted form of POSIX path of (imageContainer & reSizedName)
do shell script "sips --resampleWidth 200 " & originalFile & " --out " & outputPath
end repeat
end open
on run
display dialog "Drop some Image Files to Re-size them all to 200 pixels wide" buttons {"Aye Aye"} default button "Aye Aye"
end run
This preserves the aspect ratio of the original image, and simply re-sizes the width to 200 pixels. Hopefully you can see where you can make the changes necessary for your own workflow.
If you want to drop a folder of images as well as individual files, try this as a droplet:
on open droppings
repeat with everyDrop in droppings
if (info for everyDrop)'s folder is true then
tell application "Finder" to set allImageFiles to everyDrop's every file
repeat with eachFile in allImageFiles
my SetWidthTo200(eachFile)
end repeat
else
my SetWidthTo200(everyDrop)
end if
end repeat
end open
to SetWidthTo200(img)
set originalFile to quoted form of POSIX path of (img as text)
tell application "Finder"
set originalName to img's name
set imageContainer to (img's container as text)
end tell
set reSizedName to "200W" & originalName
set outputPath to quoted form of POSIX path of (imageContainer & reSizedName)
do shell script "sips --resampleWidth 200 " & originalFile & " --out " & outputPath
end SetWidthTo200
on run
display dialog "Drop some Image Files to Re-size them all to 200 pixels wide" buttons {"Aye Aye"} default button "Aye Aye"
end run
There is still no error-checking or checking to be sure that the files are indeed image files, so keep that in mind.
Here's a summary from this OSX Tips using automator to resize images
open "Automator"
File > New > Service
Settings:
Service received selected: "image files"
in "Finder"
in the left pane, find for action named "Get Selected Finder Items"
Next look for action "Scale Images"
If you wish to replace original, choose "Don’t Add" when it ask
"would you like to add a Copy Finder Items action", otherwise, choose add
In order to be able to choose the highest pixels before scaling, click on Options at the right of results, tick
"show this action when the workflow run"

how to remove black padded background after rotation of images

I am new in Qt. I am working on rotation of images. In my case, rotation is working fine but after rotation black padded background appears. I want to remove or hide that black background.
I am working on MAC. so I am using "Imageevent" applescript. and my script is this: tell application "Image Events".
launch
set this_image to open this_file
rotate this_image to angle 270
save this_image with icon
close this_image
end tell
besides this script i have also tried this Qt code for rotation of images:
void MyWidget::rotateLabel()
{
QPixmap pixmap(*my_label->pixmap());
QMatrix rm;
rm.rotate(90);
pixmap = pixmap.transformed(rm);
my_label->setPixmap(pixmap);
}
You can also pad images with a specified color...
set myFile to "/Users/JD/Desktop/test.png"
do shell script "sips -r 270 " & quoted form of myFile & " --padColor FFFFFF -i"
EDIT
You can save the script below as an application and drop files on it...
on open of theFiles
repeat with aFile in theFiles
set filePath to quoted form of (aFile's POSIX path)
do shell script "sips -r 270 " & filePath & " --padColor FFFFFF -i"
end repeat
end open
sips seems to keep transparent backgrounds in at least PNG files:
sips -r 270 /tmp/a.png -o /tmp/b.png
You could also use ImageMagick:
convert -rotate 270 /tmp/a.png /tmp/b.png

Resources