Folder Action to resize images in Leopard 10.5.8 - applescript

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.

Related

Apple script to export images from "Photos" application

I have albums and nested albums and folders in Photos application. I want my applescript to export images maintaining the Album or Folder structure that I have the in the application.
I tried scripts available online :
tell application "Finder"
set location_1 to (choose folder with prompt "Choose a folder to export into") as text
end tell
tell application "Photos"
set x to name of every folder
choose from list x with prompt "Choose a project to export"
set theP to item 1 of result
tell application "Finder" to make new folder at alias location_1 with properties {name:theP}
tell folder theP
set initflist to every folder
set initalist to every album
if initflist is equal to {} then
log "process albums"
processAlbums(initalist, location_1 & theP) of me
else
if initalist is not equal to {} then
log "process albums"
processAlbums(initalist, location_1 & theP) of me
end if
log "process sub folders "
processSfolders(initflist, (location_1 & theP)) of me
end if
end tell
end tell
on processAlbums(alist, apath)
tell application "Photos"
repeat with a in alist
tell a
set theimages to get media items of album a
set thename to name of a
tell application "Finder"
if not (exists folder thename in alias apath) then
make new folder at alias apath with properties {name:thename}
end if
set destination to apath & ":" & thename & ":"
end tell
with timeout of 6000 seconds
tell a
set settings to "JPEG - Original Size"
export theimages to alias destination
end tell
end timeout
end tell
end repeat
end tell
end processAlbums
on processSfolders(flist, fpath)
tell application "Photos"
repeat with a in flist
try
set thename to name of a
tell application "Finder"
if not (exists folder thename in alias fpath) then
make new folder at alias fpath with properties {name:thename}
end if
end tell
tell a
set sAlist to every album
set sflist to every folder
if sflist is equal to {} then
processAlbums(sAlist, fpath & ":" & thename) of me
else
if sAlist is not equal to {} then
processAlbums(sAlist, fpath & ":" & thename) of me
end if
processSfolders(sflist, fpath & ":" & thename) of me
end if
end tell
on error errMsg
log "error"
end try
end repeat
end tell
end processSfolders
The issue is that it gets names of only child albums and not top level albums. I have to maintain the entire structure of album or folder.
I do not know AppleScript and I tried tweaking this one but no luck so far. can I get a direction please?
You can get the name of the folders, and the albums contained in the folder, which will enable you to create the top level and child directories. Albums can only contain media items, not albums. Top level albums are classified as folders or containers. In the Applescript dictionary for Photos, it gives the definitions for these items.
tell application "Finder"
set location_1 to (choose folder with prompt "Choose a folder to export into") as text
end tell
tell application "Photos"
activate
set fds to folders
repeat with fd in fds
set fdName to name of fd
set abNames to every album of fd
if parent of fd is missing value then
my createFolders(fdName, abNames, location_1, fd)
end if
end repeat
end tell
on createFolders(fName, aAlbums, fPath, fd)
tell application "Finder"
if not (exists folder fName in alias fPath) then
make new folder with properties {name:fName} at fPath
end if
repeat with a in aAlbums
set aName to name of a
set aPath to ((fPath as alias) as text) & fName
if not (exists folder aName in alias aPath) then
make new folder with properties {name:aName} at aPath
end if
set exPath to ((aPath as alias) as text) & aName
my exportImages(a, exPath)
end repeat
end tell
tell application "Photos"
set rcFolders to every folder of fd
repeat with rcFd in rcFolders
set rcAlbums to every album of rcFd
set rcName to name of rcFd
set rcPath to ((fPath as alias) as text) & fName
my createFolders(rcName, rcAlbums, rcPath, rcFd)
end repeat
end tell
end createFolders
on exportImages(photoAlbum, destination)
tell application "Photos"
set theimages to get media items of photoAlbum
with timeout of 6000 seconds
tell photoAlbum
set settings to "JPEG - Original Size"
export theimages to alias destination
end tell
end timeout
end tell
end exportImages
EDIT - Error Handling
To handle errors, locate the command that is causing the error and wrap it in a try block. Solution could be to quit the application, so that the process will end, and maybe add a short delay and then continue with the script.
try
export theimages to alias destination
on error
-- statements to execute in case of error
error "The exporting of images failed to complete"
quit
end try
From the developer reference - When a command fails to complete in the allotted time (whether the default of two minutes, or a time set by a with timeout statement), AppleScript stops running the script and returns the error "event timed out". AppleScript does not cancel the operation—it merely stops execution of the script. If you want the script to continue, you can wrap the statements in a try statement. However, whether your script can send a command to cancel an offending lengthy operation after a timeout is dependent on the application that is performing the command. Further info regarding try statements.

AppleScript find folder with specific file

I have a folder with file /resources/video.mov. This folder with video can located in any place, like /Users/UserName/Desktop/resources/video.mov or /Applications/resources/video.mov and etc. I need to find this folder with video and copy to specific place. I can't find path of folder with video to copy it.
tell application "Finder"
duplicate items in folder "_locatedPath_" to folder "_destiontionPath_" with replacing
end tell
This works for me using the latest version of Sierra
Change the value of variable destinationFolder to the output folder of your choice
property theContainer : missing value
property containingFolder : "resources" -- change if needed
property theSearch : "video.mov" -- change if needed
property destinationFolder : (path to desktop as text) -- change if needed
set findFile to do shell script "mdfind -name " & theSearch
repeat with i from 1 to number of paragraphs in findFile
set this_item to POSIX file (paragraph i of findFile) as alias
tell application "Finder"
if name of this_item is theSearch then
set theContainer to the container of this_item as text
if theContainer contains containingFolder then
set resultObject to duplicate this_item ¬
to destinationFolder ¬
replacing true ¬
routing suppressed true ¬
with exact copy
end if
end if
end tell
end repeat

how to fix 100's of alias' on mac after migration?

I really hope someone can help me out with this. I recently moved from one mac to another and did a clean install. I have several folders with hundreds of alias (how do you say the plural of alias?)...
The original file path is "/Volumes/Media Drive/Ableton/Warped Tracks/", and the new path needs to be "/users/joel/Music/Ableton Projects/Warped Tracks"
I see how to fix them one at a time, but that would take hours. I tried this applescript, but had no luck:
https://apple.stackexchange.com/questions/2656/how-do-i-fix-failed-aliases
Can anyone give me a better applescript or another solution? As I mentioned, I tried this applescript:
tell application "Finder"
set these_items to the selection
end tell
repeat with i from 1 to the count of these_items
set this_item to (item i of these_items) as alias
set this_info to info for this_item
if class of this_item is alias then
tell application "Finder"
set original_file to original item of this_item
set this_alias_file_name to displayed name of this_item
set container_folder to container of this_item
set the_path to the POSIX path of (original_file as alias)
set new_path to my replaceText("/Volumes/Media Drive/Ableton/Warped Tracks/", "/users/joel/Music/Ableton Projects/Warped Tracks", the_path)
move this_item to trash
try
make new alias file at container_folder to (POSIX file new_path) with properties {name:this_alias_file_name}
on error errMsg number errorNumber
if errorNumber is -10000 then -- new original file not found, try relinking to old
try
make new alias file at container_folder to (POSIX file the_path) with properties {name:this_alias_file_name}
on error errMsg number errorNumber
if errorNumber is -10000 then -- old original not found. link's dead Jim
display dialog "The original file for alias " & this_alias_file_name & " was not found."
else
display dialog "An unknown error occurred: " & errorNumber as text
end if
end try
else
display dialog "An unknown error occurred: " & errorNumber as text
end if
end try
end tell
end if
end repeat
on replaceText(find, replace, subject)
set prevTIDs to text item delimiters of AppleScript
set text item delimiters of AppleScript to find
set subject to text items of subject
set text item delimiters of AppleScript to replace
set subject to "" & subject
set text item delimiters of AppleScript to prevTIDs
return subject
end replaceText
Any help would be greatly appreciated.
Edit: I think the problem with the applescript for me is that I have folders further down the path that all are different, and THOSE each contain the individual alias files. IE:
"/users/joel/Music/Ableton Projects/Warped Tracks/Folder A/file.alias",/users/joel/Music/Ableton Projects/Warped Tracks/Folder B/file2.alias", etc, etc
I had same issue years ago (transfer between 2 media centers), and I made this program : it asks for folder were all broken alias are and then try to find again original path to rebuild them.
the thing is that any applescript instruction about alias gives error when link is broken, so you must use Finder info window to read original path without error when the link is already broken:
(this program assumes that original file name is unique)
-- Select main folder
tell application "Finder" to set Mon_Dossier to ((choose folder with prompt "Select top folder:" without invisibles) as alias) as string
-- repair alias in this folder and all subsequent folders (entire contents)
tell application "Finder" to set Mes_Alias to every file of entire contents of folder Mon_Dossier whose class is alias file
-- loop on each alias of the folder
repeat with Mon_Alias in Mes_Alias
-- found the original file path of Mon_Alias
-- try first with standard alias call
set F_Source to ""
try
tell application "Finder" to set F_Source to original item of Mon_Alias
end try
if F_Source is "" then
-- the link to original file is broken, then use on windows info method
set F_Source to Origine_Alias(Mon_Alias)
set F_Original to Decompose(F_Source)
-- no need to look original file as is, becuase the link is broken (path changed ?)
-- then directly search for the same file without extension
set Cible to ((chemin of F_Original) as string) & ((Nom of F_Original) as string)
tell application "Finder"
if exists file Cible then
-- file is found without extension
-- then delete alias and create new alias with same name and in same folder
set A_Nom to name of Mon_Alias
set A_Dossier to folder of Mon_Alias
delete Mon_Alias
set Nouvel_Alias to make alias to Cible at A_Dossier
set name of Nouvel_Alias to A_Nom
else
SLog("Alias=" & (Mon_Alias as string) & " File not found=" & Cible)
end if
end tell
else
-- the alias link is still valid : nothing to do ! go to next alias..
end if
end repeat
-- end main program
-- sub routine to find passe of broken link (original path/file can't be found)
-- the result is a unix path like folder/sub_folder/file
on Origine_Alias(F_Alias)
set R to ""
tell application "Finder" to open information window of file (F_Alias as text)
tell application "System Events" to tell process "Finder" to set R to value of static text 19 of scroll area 1 of front window
tell application "Finder" to close front window
return R
end Origine_Alias
-- sub routine to extract, from unix file path, the path, the file name and its extension: result is sent back in a record
-- Warning : we can't use "Posix file of" becuase the path and the file are non longer valid ! (then Posix gives error)
on Decompose(Local_F)
--search the first "." from right to find extension
set X to length of Local_F
repeat while (character X of Local_F is not ".") and (X > 0)
set X to X - 1
end repeat
if X > 0 then
set L_Ext to text (X + 1) thru (length of Local_F) of Local_F
set Local_F to text 1 thru (X - 1) of Local_F
else
L_Ext = "" -- "." not found, then no extension !
end if
-- search first "/" from the right to extract file name
set X to length of Local_F
repeat while (character X of Local_F is not "/")
set X to X - 1
end repeat
set L_Nom to text (X + 1) thru (length of Local_F) of Local_F
set Local_F to text 1 thru (X) of Local_F
try
set L_Chemin to POSIX file Local_F
end try
return {chemin:L_Chemin, Nom:L_Nom, Ext:L_Ext}
end Decompose
-- sub routine log (text log file on desktop)
on SLog(msg)
set the my_log to ¬
((path to desktop) as text) & "My_logfile.txt"
try
-- open file. create it if not yet exist
open for access file the my_log with write permission
-- add text at end of file
write (msg & return) to file the my_log starting at eof
close access file the my_log
on error
try
close access file the my_log
end try
end try
end SLog

Copy multiple files using AppleScript

I have to duplicate multiple files using an AppleScript. What this script should do is first, ask the user to select the folder which contains the files that have to be duplicated. Second, show a list of all of the files that there're in the folder that user have selected. In this step, the user can select multiple files. And the last step is duplicate the files. Here's t'he script I'm using:
--Get the folder
set theFolder to (choose folder with prompt "Select the folder that contains the files to copy. In the next step you'll be able to select the files to copy.") as text
--Get the path to de destination folder of the files
set destination_folder to (path to home folder) as text
--Generate the list of files inside theFolder
tell application "Finder"
set theItems to items of folder theFolder
set theNames to {}
repeat with anItem in theItems
set end of theNames to name of anItem
end repeat
end tell
-Let user select the files of the list
choose from list theNames with prompt "Select the files" OK button name "OK" cancel button name "Cancel" with multiple selections allowed
tell result
if it is false then error number -128 -- cancel
set theChoices to it
end tell
if (count of theChoices) is greater than or equal to 1 then
repeat with aChoice in theChoices
set thisItem to theFolder & aChoice
-- do something with thisItem
duplicate thisItem to destination_folder
end repeat
end if
The problem is that when the srcipt has to run the line "copy thisItem to destination_folder" it crashes. Here's the oputput that generates AppleScript Editor when I try to run:
tell application "AppleScript Editor"
choose from list {"Obres.xlsx", "Programa_sardanes", "Sardanes.xlsx"} with prompt "Escull els arxius o l'arxiu que vols afegir" OK button name "Acceptar" cancel button name "Cancelar" with multiple selections allowed
--> {"Sardanes.xlsx"}
-- 'core'\'clon'{ 'insh':'utxt'("Macintosh HD:Users:Joan:"), '----':'utxt'("Macintosh HD:Users:Joan:MEGA:Sardanes.xlsx"), &'subj':null(), &'csig':65536 }
--> error number -1700 from "Macintosh HD:Users:Joan:MEGA:Sardanes.xlsx" to reference
Result:
error "Can't generate \"Macintosh HD:Users:Joan:MEGA:Sardanes.xlsx\" on the type reference." number -1700 from "Macintosh HD:Users:Joan:MEGA:Sardanes.xlsx" to reference
I have been trying several hours to solve this problem but I don't know where is the error on the script. I hope someone could help me. And if someone knows a much more simple way to do this would be helpful also. Thank you!
I made some small changes to your script and it should work now...
Basically, you were missing a couple small portions. The "duplicate" command is a function of the "Finder", so I added a "Tell application "Finder"" to the duplicate portion. You were also storing your path to your file and folder as text, I modified them to be referenced as "alias".
on run
--Get the folder
set theFolder to (choose folder with prompt "Select the folder that contains the files to copy. In the next step you'll be able to select the files to copy.") as text
--Get the path to de destination folder of the files
set destination_folder to (path to home folder)
--Generate the list of files inside theFolder
tell application "Finder"
set theItems to items of folder theFolder
set theNames to {}
repeat with anItem in theItems
set end of theNames to name of anItem
end repeat
end tell
--Let user select the files of the list
choose from list theNames with prompt "Select the files" OK button name "OK" cancel button name "Cancel" with multiple selections allowed
tell result
if it is false then error number -128 -- cancel
set theChoices to it
end tell
if (count of theChoices) is greater than or equal to 1 then
repeat with aChoice in theChoices
set thisItem to (theFolder & aChoice) as alias
-- do something with thisItem
tell application "Finder" to duplicate thisItem to destination_folder
end repeat
end if
end run

AppleScript: Create new folder from file name and move file into that folder

Basically, I'm trying to create a folder action in Automator so whenever a file is added to a specific folder, it will create a subfolder that matches the filename (without the extension), then move the file into that subfolder.
So far, I have successfully used a post from this site (Create new folder named with a specified file name in Automator) to create a script that will create the new folder. However, I have been unable to modify the script to move the original file into the new folder.
Any help would be appreciated. Here is the full script I am working with for reference:
on run {input, parameters} -- make new folders from base file names
set output to {}
repeat with anItem in the input -- step through each item in the input
set anItem to anItem as text
tell application "System Events" to tell disk item anItem
set theContainer to path of container
set {theName, theExtension} to {name, name extension}
end tell
if theExtension is in {missing value, ""} then
set theExtension to ""
else
set theExtension to "." & theExtension
end if
set theName to text 1 thru -((count theExtension) + 1) of theName -- the name part
tell application "Finder"
make new folder at folder theContainer with properties {name:theName}
set end of output to result as alias
end tell
end repeat
return input -- or output
end run
Thanks in advance!
Add this folder action to your target folder:
on adding folder items to theFolder after receiving theFiles
repeat with aFile in theFiles
tell application "System Events" to set {Nm, Ex, pPath} to aFile's {name, name extension, POSIX path of container}
set BN to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
set thePath to (pPath & "/" & BN & "/" as text)
do shell script "mkdir -p " & quoted form of thePath
delay 0.5
tell application "Finder" to move aFile to POSIX file thePath
end repeat
end adding folder items to

Resources