How to sort images by width in Applescript? - applescript

I would like to sort my pictures by size, ad it is easiest to do so by width. I would like to get images with a width larger than 1919px and put it in another folder. I have googled and tried things for hours with no luck.
I've been getting this error: error "Image Events got an error: Can’t make item 1 of dimensions of image \"1mouwi.jpg\" into type specifier." number -1700 from item 1 of dimensions of image "1mouwi.jpg" to specifier at item 1 in the repeat loop. any help on how to fix this?
My Code:
set picFolder to alias ":Users:USERNAME:Pictures:DESKTOPS:"
set hdFolder to alias ":Users:USERNAME:Pictures:DESKTOPS_HD:"
tell application "System Events"
set photos1 to path of files of picFolder
set num to count of photos1
set photos to items 2 thru num of photos1
end tell
set hd to {}
repeat with imgPath in photos
set imgAlias to alias imgPath
tell application "Image Events"
set img to open imgPath
set width to item 1 of dimensions of img
if width > 1919.0 then
set end of hd to imgAlias
end if
close img
end tell
end repeat
tell application "Finder"
move hd to hdFolder
end tell

A simple solution is to use the "get" command and parenthesis. In general "get" is understood so you normally don't have to use it in commands... but a quirk in applescript requires you to explicitly use it sometimes... especially when you have multiple commands in one line. Also the parenthesis ensure the multiple operations of the width line of code are performed in the right order
set width to item 1 of (get dimensions of img)
However there's a few other optimizations you could use so here's how I would write your script.
set picFolder to (path to pictures folder as text) & "DESKTOPS:"
set hdFolder to (path to pictures folder as text) & "DESKTOPS_HD:"
tell application "System Events" to set photos1 to path of files of folder picFolder
set photos to items 2 thru end of photos1
set hd to {}
repeat with imgPath in photos
set imgAlias to alias imgPath
tell application "Image Events"
set img to open imgAlias
set width to item 1 of (get dimensions of img)
close img
end tell
if width > 1919 then
set end of hd to imgAlias
end if
end repeat
tell application "Finder"
if hd is not {} then move hd to folder hdFolder
end tell

You might just use mdls -rn kMDItemPixelWidth in the shell:
for f in ~/Pictures/DESKTOPS/*; do [[ $(mdls -rn kMDItemPixelWidth "$f") -ge 1920 ]] && mv "$f" ~/Pictures/DESKTOPS_HD/; done
If mdls doesn't show the sizes of some images, try using ImageMagick or sips:
brew install imagemagick; identify -format %w input.png
sips --getProperty pixelWidth input.png | awk 'END{print $NF}'

It works if you split up the dimension and width into two separate lines.
tell application "Image Events"
set img to open imgPath
set dim to dimensions of img
set width to item 1 of dim
[...]
end

Related

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"

Applescript CS5 and CS6 export with save for web will not work

I am at my wit's end. I have tried all variations to get this script to work. The error I get is Adobe Photoshop CS6 got an error: Can’t get current document. and the highlighted script error is my "export in file newFileName.." block. I've tried putting alias in different positions, using file, not using file. Also I get this error message, but the actual script seems to stop working right after "set docName to name of docRef"
And basically I just copied this code from another script that was working fine and just changed a save this file... to a export this file...
-- set the folders that you want to use
set inputFolder to choose folder with prompt "Choose the folder of images to downsize."
set pathToDesktop to (path to desktop folder as string)
set outputFolder to pathToDesktop & "PhotoshopRetina:"
tell application "Finder"
set filesList to files in folder inputFolder
if not (exists folder outputFolder) then
make new folder at desktop with properties {name:"PhotoshopRetina"}
end if
end tell
with timeout of 86400 seconds
tell application "Adobe Photoshop CS6"
set display dialogs to never
close every document saving no
end tell
repeat with aFile in filesList
tell application "Finder"
-- The step below is important because the 'aFile' reference as returned by
-- Finder associates the file with Finder and not Photoshop. By converting
-- the reference below 'as alias', the reference used by 'open' will be
-- correctly handled by Photoshop rather than Finder.
set theFile to aFile as string
set theFileName to name of aFile
set theFileInfo to info for alias theFile
if kind of theFileInfo is "Adobe Photoshop JPEG file" then
my retinaDisplay(theFile)
end if
end tell
end repeat
end timeout
end
on retinaDisplay(theFile)
tell application "Adobe Photoshop CS6"
open alias theFile
set docRef to the current document
-- Convert the document to a document mode that supports saving as jpeg
if (mode of docRef is not RGB) then
change mode docRef to RGB
end if
tell docRef
set color profile kind to none
end tell
set infoRef to get info of docRef
set docName to name of docRef
set docBaseName to getBaseName(docName) of me
set newFileName to (my outputFolder as string) & docBaseName & ".jpg"
tell current document
export in file newFileName as save for web with options {class:save for web export options, web format:JPEG, embed color profile:false, quality:45} with copying
end tell
close current document without saving
end tell
end retinaDisplay
-- Returns the document name without extension (if present)
on getBaseName(fName)
set baseName to fName
repeat with idx from 1 to (length of fName)
if (item idx of fName = ".") then
set baseName to (items 1 thru (idx - 1) of fName) as string
exit repeat
end if
end repeat
return baseName
end getBaseName
end
If I open an image in photoshop I can run this code with no errors.
set f to (path to desktop as text) & "test.jpg"
tell application "Adobe Photoshop CS6"
tell current document
export in file f as save for web
end tell
end tell
However, if I additionally add your "with options" code then I get your error. I don't even know what the "with copying" part is. I don't think that means anything to photoshop. So the problem is not with the "current document". The problem is with your options. You must be doing that part wrong.
Good luck.

FileZilla and applescript

I am making an applescript that converts a folder of flv and f4v files to mp4 files and then uploads the to a server via filezilla. How would I use applescript to upload to a server through Filezilla? Here is my code:
--Install handbrakecli into /usr/bin/
--on adding folder items to this_folder after receiving these_items
with timeout of (720 * 60) seconds
tell application "Finder"
--Get all flv and f4v files that have no label color yet, meaning it hasn't been processed
set allFiles to every file of entire contents of ("Macintosh HD:Users:Chase:auto_convert:nope" as alias) whose ((name extension is "flv" or name extension is "f4v") and label index is 0)
--Repeat for all files in above folder
repeat with i from 1 to number of items in allFiles
set currentFile to (item i of allFiles)
try
--label to indicate processing
set label index of currentFile to 3
--Assemble original and new file paths
set origFilepath to quoted form of POSIX path of (currentFile as alias)
set newFilepath to (characters 1 thru -5 of origFilepath as string) & "mp4'"
--Start the conversion
tell application "Terminal"
do shell script "HandBrakeCLI -i " & origFilepath & " -o " & newFilepath
end tell
--Set the label to red because this is the file that has been converted
set label index of currentFile to 6
--Remove the old file
on error errmsg
--Set the label to red to indicate failure
set label index of currentFile to 2
end try
end repeat
set extensionToFind to "mp4"
set topLevelFolder to "Macintosh HD:Users:Chase:auto_convert:nope" as text
set pathCount to count of topLevelFolder
set mp4Files to files of entire contents of folder topLevelFolder whose name extension is extensionToFind
if mp4Files is {} then return
set mp4Folder to "Macintosh HD:Users:Chase:auto_convert:yep"
move mp4Files to mp4Folder
end tell
end timeout
--end adding folder items to
Not a good idea, because Filezilla has no applescript support. I've always been surprised that Cyberduck doesn't either. But see:
http://discussions.apple.com/thread/2588937?start=0&tstart=0
.... on which there are good directions; curl in shell, or (at the end of the page) URL Access Scripting, which is a scripting addition that should be installed on your Mac. URL Access Scripting example:
tell application "URL Access Scripting"
upload filepathtoUpload to "ftp://username:password#domain.com/SOME/PATH/filename.jpg" replacing yes without binhexing
end tell

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

Folder Action to resize images in Leopard 10.5.8

I know nothing about AppleScript, so please forgive me.
Goal is to create a folder that our graphics guy can drop stock photos into and have them resized to 1280. The chosen folder is a network folder, so don't know if that's part of the issue or not. He will be pasting the images into the folder from his Windows workstation.
Here is what I have pieced together so far:
on adding folder items to this_folder after receiving added_items
repeat with this_item in added_items
try
rescale_and_save(this_item)
end try
end repeat
end adding folder items to
to rescale_and_save(this_item)
tell application "Image Events"
launch
set the target_height to 1280
-- open the image file
set this_image to open this_item
set typ to this_image's file type
copy dimensions of this_image to {current_width, current_height}
if current_height is greater than current_width then
scale this_image to size target_height
else
-- figure out new height
-- y2 = (y1 * x2) / x1
set the new_width to (current_width * target_height) / current_height
scale this_image to size new_width
end if
tell application "Finder" to set new_item to ¬
(container of this_item as string) & "ex" & (name of this_item)
save this_image in new_item as typ
end tell
end rescale_and_save
I've right clicked on the folder, enabled folder actions, and added my script. I copy in the test file but nothing happens.
Any ideas?
EDIT:
I looked at the samples and came up with the following script that WORKS!:
property done_foldername : "Scaled Images"
property target_height : 1280
-- the list of file types which will be processed
-- eg: {"PICT", "JPEG", "TIFF", "GIFf"}
property type_list : {"JPEG", "TIFF", "PNGf"}
-- since file types are optional in Mac OS X,
-- check the name extension if there is no file type
-- NOTE: do not use periods (.) with the items in the name extensions list
-- eg: {"txt", "text", "jpg", "jpeg"}, NOT: {".txt", ".text", ".jpg", ".jpeg"}
property extension_list : {"jpg", "jpeg", "tif", "tiff", "png"}
on adding folder items to this_folder after receiving these_items
-- CHECK FOR THE DESTINATION FOLDER WITHIN THE ATTACHED FOLDER
-- IF IT DOESN'T EXIST, THEN CREATE IT
tell application "Finder"
if not (exists folder done_foldername of this_folder) then
make new folder at this_folder with properties {name:done_foldername}
set current view of container window of this_folder to list view
end if
set the target_folder to folder done_foldername of this_folder
end tell
-- PROCESS EACH OF THE ITEMS ADDED TO THE ATTACHED FOLDER
try
repeat with i from 1 to number of items in these_items
set this_item to item i of these_items
set the item_info to the info for this_item
-- CHECK TO SEE IF THE ITEM IS AN IMAGE FILE OF THE ACCEPTED FILE TYPE
if (alias of the item_info is false and the file type of the item_info is in the type_list) or (the name extension of the item_info is in the extension_list) then
tell application "Finder"
-- LOOK FOR EXISTING MATCHING ITEMS IN THE DESTINATION FOLDER
-- IF THERE ARE MATCHES, THEN RENAME THE CONFLICTING FILES INCREMENTALLY
my resolve_conflicts(this_item, target_folder)
-- MOVE THE ITEM TO THE DESTINATION FOLDER
set the target_file to (move this_item to the target_folder with replacing) as alias
end tell
-- PROCESS THE ITEM
process_item(target_file)
end if
end repeat
on error error_message number error_number
if the error_number is not -128 then
tell application "Finder"
activate
display dialog error_message buttons {"Cancel"} default button 1 giving up after 120
end tell
end if
end try
end adding folder items to
on resolve_conflicts(this_item, target_folder)
tell application "Finder"
set the file_name to the name of this_item
if (exists document file file_name of target_folder) then
set file_extension to the name extension of this_item
if the file_extension is "" then
set the trimmed_name to the file_name
else
set the trimmed_name to text 1 thru -((length of file_extension) + 2) of the file_name
end if
set the name_increment to 1
repeat
set the new_name to (the trimmed_name & "." & (name_increment as string) & "." & file_extension) as string
if not (exists document file new_name of the target_folder) then
-- rename to conflicting file
set the name of document file file_name of the target_folder to the new_name
exit repeat
else
set the name_increment to the name_increment + 1
end if
end repeat
end if
end tell
end resolve_conflicts
-- this sub-routine processes files
on process_item(this_item)
-- NOTE that the variable this_item is a file reference in alias format
-- FILE PROCESSING STATEMENTS GOES HERE
try
-- convert alias reference to string
set this_item to this_item as string
with timeout of 900 seconds
tell application "Image Events"
launch -- always use with Folder Actions
set this_image to open file this_item
scale this_image to size target_height
save this_image with icon
close this_image
end tell
end timeout
on error error_message
tell application "Finder"
activate
display dialog error_message buttons {"Cancel"} default button 1 giving up after 120
end tell
end try
end process_item
I just tested your script on a folder dropping 1 image in, and it turns out it runs repeatedly because the resulting (resized) image is also added to that folder. Here's what it looked like after a couple of seconds, before I interrupted it:
You should have a look at the default image processing scripts inside /Library/Scripts/Folder Action Scripts and maybe use one of them as a template. They basically use a sub-folder for the processed images and contain some possibly useful filename conflict resolving function, too.

Resources