I am trying to achieve some automation in my current workflow. I'd like to drop images to my applescript application, then have it autoresize to the size as set by the user.
I prompt the user a dialog, where one can enter the pixelsize for width, then have the script do the donkey work.
For some reason it is not running properly, and for the life of my i can't figure out why.
Any and all help is very much appreciated!
Here's the script:
display dialog "What is the desired size?" default answer "64"
set my_answer to text returned of result
on open some_items
repeat with this_item in some_items
try
rescale_and_save(this_item)
end try
end repeat
end open
to rescale_and_save(this_item)
tell application "Image Events"
launch
set the target_width to my_answer
-- 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_width is greater than current_height then
scale this_image to size target_width
else
-- figure out new height
-- y2 = (y1 * x2) / x1
set the new_height to (current_height * target_width) / current_width
scale this_image to size new_height
end if
tell application "Finder" to set new_item to ¬
(container of this_item as string) & "scaled." & (name of this_item)
save this_image in new_item as typ
end tell
end rescale_and_save
I wrote this script a while ago. It will re-sample an image so its largest dimension is the input value.
on open of myFiles
set my_answer to text returned of (display dialog "What is the desired size?" default answer "64")
repeat with aFile in myFiles
set filePath to aFile's POSIX path
set bPath to (do shell script "dirname " & quoted form of filePath)
tell application "System Events" to set {fileName, fileExt} to {name, name extension} of aFile
set baseName to text 1 thru ((get offset of "." & fileExt in fileName) - 1) of fileName
do shell script "sips " & quoted form of aFile's POSIX path & " -Z " & my_answer & " --out " & quoted form of (bPath & "/" & baseName & "-" & my_answer & "." & fileExt as text)
end repeat
end open
Related
I am writing an AppleScript to handle some MTS files. The script recursively iterates through the subfolders of the top-level folder "Volumes:G-Drive:video". The subfolders are arranged into year folders, starting with the folder named "2005" for the year 2005. The runtime error is occurring with the very first folder "2005" that the script tries to iterate. I suspected it is something to do with how I am handling aliases and text, but I am stumped at this point how to fix it. The error at runtime is this:
Can’t make {alias "G-DRIVE:video:", "2005:"} into type integer.
I don't know where in my code an integer type comes into play so as to get this error. Script Editor doesn't point me to the location of the runtime error in the code, so i don't know how to figure out which line is causing this either.
set folderName to "Volumes:G-Drive:video" as alias
my processFolder("", folderName)
on processFolder(root, folderNameToProcess)
tell application "Finder"
set theItems to every file of folder (root & folderNameToProcess)
repeat with theFile in theItems
set Nm to name of theFile as text
set Ex to name extension of theFile
if Nm does not contain "-c" and Ex is "MTS" then
set NmMinusExt to my remove_extension(Nm)
set logMsg to "Deleting " & Nm
my logThis(logMsg)
tell application "Finder" to delete theFile
end if
end repeat
set theItems to every file of folder (root & folderNameToProcess)
repeat with theFile in theItems
set Nm to name of theFile as text
set Ex to name extension of theFile
--tell (info for theFile) to set {Nm, Ex} to {name, name extension}
if Nm contains "-c" and Ex is "MTS" then
set NmMinusExt to my remove_extension(Nm)
set shortNm to my remove_lastTwoCharacters(NmMinusExt)
set name of theFile to shortNm & ".MTS" as text
set logMsg to "Renaming " & Nm
my logThis(logMsg)
--set lastTwoLetters to characters (((length of Nm) - 2) as number) thru (((length of Nm) - 0) as number) of (Nm as text)
--if lastTwoLetters is "-c" then
--display notification lastTwoLetters
--end if
end if
end repeat
set theFolders to name of folders of folder (root & folderNameToProcess)
repeat with theFolder in theFolders
copy theFolder as string to TheFolderName
display notification "found folder named: " & TheFolderName
set firstChar to (text 1 thru 1 of TheFolderName)
if firstChar is not "." then
--display dialog (folderNameToProcess & TheFolderName & ":")
try
my processFolder(folderNameToProcess, TheFolderName & ":")
on error errStr number errorNumber
display dialog errStr
end try
end if
end repeat
end tell
return
end processFolder
on remove_extension(this_name)
if this_name contains "." then
set this_name to ¬
(the reverse of every character of this_name) as string
set x to the offset of "." in this_name
set this_name to (text (x + 1) thru -1 of this_name)
set this_name to (the reverse of every character of this_name) as string
end if
return this_name
end remove_extension
on remove_lastTwoCharacters(this_name)
set this_name to ¬
(the reverse of every character of this_name) as string
set this_name to (text 3 thru -1 of this_name)
set this_name to (the reverse of every character of this_name) as string
return this_name
end remove_lastTwoCharacters
The Events pane of Script Editor produces the following trace:
tell application "Finder"
get every file of folder "G-DRIVE:video:"
get every file of folder "G-DRIVE:video:"
get name of every folder of folder "G-DRIVE:video:"
display notification "found folder named: 2005"
end tell
tell application "Script Editor"
display notification "found folder named: 2005"
end tell
tell application "Finder"
get every file of folder {alias "G-DRIVE:video:", "2005:"}
display dialog "Finder got an error: Can’t make {alias \"G-DRIVE:video:\", \"2005:\"} into type integer."
folderName is an alias. The attempt to concatenate an alias and a string creates a list which the error indicates.
The solution is to use only (HFS) string paths.
Replace
set folderName to "Volumes:G-Drive:video" as alias
with
set folderName to "G-Drive:video:"
The trailing colon is crucial to be able to add path components
The AppleScript I'm making extracts the frames from a gif file and puts the individual images in a folder inside the application's contents. It then changes the desktop background rapidly to the images inside the folder, hence giving you a gif for a wallpaper. However, I can't figure out how to extract the gif files to the folder in the application. This is what I have so far:
on delay duration
set endTime to (current date) + duration
repeat while (current date) is less than endTime
tell AppleScript to delay duration
end repeat
end delay
set gifFiles to choose file of type "com.compuserve.gif" with prompt "Select GIF"
tell application "System Events" to set gifFileName to name of gifFiles
set dest to quoted form of POSIX path of (path to me) & "Contents:Resources:Gif"
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
repeat
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 01.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 02.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 03.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 04.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
delay 0.05
try
set desktop_image to (path to me as string) & "Contents:Resources:Gif:" & gifFileName & " 05.gif"
tell application "Finder" to set the desktop picture to desktop_image
end try
end repeat
There are some issues in the script.
choose file returns a single file. The repeat loop repeat with f in gifFiles breaks the script.
The proper POSIX path to the destination folder is
set dest to quoted form of (POSIX path of (path to me) & "Contents/Resources/Gif")
A slash must be added when composing the file path
Try this, the script assumes that the folder Gif in the Resources folder exists.
set gifFile to choose file of type "com.compuserve.gif" with prompt "Select GIF"
tell application "System Events" to set gifFileName to name of gifFile
set dest to quoted form of (POSIX path of (path to me) & "Contents/Resources/Gif")
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)"
do shell script "/usr/bin/python -c " & pScript & " " & (quoted form of POSIX path of gifFile) & " " & dest
tell application "Finder"
set extractedGiFFiles to files of folder ((path to me as text) & "Contents:Resources:Gif:")
repeat
repeat with aFile in extractedGiFFiles
set the desktop picture to aFile
delay 0.05
end repeat
end repeat
end tell
I am new to applescript. I want to develop an application in applescript.
Below is my code. And while running it, it's showing finder that can't make alias. Kindly help me.
property script_name : "image Tracker"
property script_description : "image property data finder"
--set the_folder to (choose folder with prompt "Select the folder for get the image property:") as Unicode text
--set the_folder to quoted form of POSIX path of (choose folder with prompt "Select the folder for get the image property:")
set the_folder to (choose folder)
copy {"jpg", "png", "eps", "ai", "tif", "psd", "gif"} to validExtentions
tell application "Finder" to set fPaths to file the_folder
repeat with thisFilePath in fPaths
if name extension of thisFilePath is in validExtensions then
try
tell application "Image Events"
-- start the Image Events application
launch
-- open the image file
set this_image to open this_file
-- extract the properties record
set the props_rec to the properties of this_image
-- purge the open image data
close this_image
-- extract the property values from the record
set the image_info to ""
set the image_info to the image_info & ¬
"Name: " & (name of props_rec) & return
set the image_info to the image_info & ¬
"*********************************************" & return
set the image_info to the image_info & ¬
"File: " & (path of image file of props_rec) & return
set the image_info to the image_info & ¬
"File Type: " & (file type of props_rec) & return
set the image_info to the image_info & ¬
"Res: " & item 1 of (resolution of props_rec) & return
set the image_info to the image_info & ¬
"Color Space: " & (color space of props_rec) & return
copy (dimensions of props_rec) to {x, y}
set the image_info to the image_info & ¬
"Dimemsions: " & x & ", " & y
end tell
on error error_message
display dialog error_message
end try
end if
end repeat
set myfile to open for access ("Macintosh HD:Users:varghese.pt:Desktop:") & "image_data.txt" with write permission
write image_info to myfile
close access myfile
If anyone found the answer, please send me the details.
Thanks in advance.
Nidhin Joseph
Let me say up front: Unfortunately, in general, AppleScript is a finicky beast, and sometimes trial and error are your only friends.
There are several problems with your code - some obvious, one not:
validExtentions is misspelled in the copy {"jpg ... statement - you later refer to with the (correctly spelled) name validExtensions
In the tell application "Finder" command, you must replace file with folder.
In command set this_image to open this_file, you must replace this_file with (thisFilePath as text). NOTE: Parenthesizing and as text is crucial, as the file will otherwise be opened by Finder (and therefore open in Preview.app) - don't ask me WHY this is so.
I also suggest replacing the hard-coded path in the write-to-file command with (path to desktop as text) & "image_data.txt"
If we put it all together, we get:
copy {"jpg", "png", "eps", "ai", "tif", "psd", "gif"} to validExtensions
set the_folder to (choose folder)
tell application "Finder" to repeat with thisFilePath in folder the_folder
if name extension of thisFilePath is in validExtensions then
try
tell application "Image Events"
# start the Image Events application
launch
# open the image file
# set this_image to open thisFilePath
set this_image to open (thisFilePath as text)
# extract the properties record
set the props_rec to the properties of this_image
# purge the open image data
close this_image
# extract the property values from the record
set the image_info to ""
set the image_info to the image_info & ¬
"Name: " & (name of props_rec) & return
set the image_info to the image_info & ¬
"*********************************************" & return
set the image_info to the image_info & ¬
"File: " & (path of image file of props_rec) & return
set the image_info to the image_info & ¬
"File Type: " & (file type of props_rec) & return
set the image_info to the image_info & ¬
"Res: " & item 1 of (resolution of props_rec) & return
set the image_info to the image_info & ¬
"Color Space: " & (color space of props_rec) & return
copy (dimensions of props_rec) to {x, y}
set the image_info to the image_info & ¬
"Dimensions: " & x & ", " & y
# my dlog(image_info)
end tell
on error error_message
display dialog error_message
end try
end if
end repeat
set myfile to open for access (path to desktop as text) & "image_data.txt" with write permission
write image_info to myfile
close access myfile
Finally, you can improve the performance of your code by switching from enumerating files in the Finder context to enumerating in the System Events context:
If you substitute the following two lines for their current counterparts in the code above, your script will run much more quickly. Why, you ask? Again, I do not know.
tell application "System Events" to repeat with thisFilePath in alias (the_folder as text)
set this_image to open (get path of thisFilePath)
Anyone of you guys could point me to why this applescript (which was working on snow leopard) does not work anymore on 10.7 Lion.
It intend to copy the file named "folder.jpg" from each album folder into ID3 tags of selected mp3 in iTunes.
property tempfile : ((path to temporary items as string) & "itunespicturefile_temporaire.pict")
global vPictFolder
tell application "iTunes"
set v_TrackSelection to selection
if v_TrackSelection is not {} then
repeat with vTrack in v_TrackSelection
set vPictFolder to my (ParentFromPath(location of vTrack as string)) as text
set thisPict to my getpictData("folder.jpg")
if thisPict is not "" then
delete artworks of vTrack
set data of artwork 1 of vTrack to (thisPict)
end if
end repeat
else
display dialog ("select tracks first !")
end if
end tell
on getpictData(vAlbumpictName)
tell application "Finder" to tell file vAlbumpictName of folder vPictFolder to if exists then
set t_file to it as string
else
display dialog vPictFolder & vAlbumpictName
return ""
end if
do shell script "/opt/local/bin/convert " & quoted form of POSIX path of t_file & " " & quoted form of POSIX path of tempfile
display dialog "ok"
return read (tempfile as alias) from 513 as picture
end getpictData
on ParentFromPath(thePath)
set wantPath to true
set thePath to (thePath as text)
set saveDelim to AppleScript's text item delimiters
set AppleScript's text item delimiters to {":"}
set pathAsList to text items of thePath
if the last character of thePath is ":" then
set idx to (the number of text items in thePath) - 2
else
set idx to -2
end if
if wantPath then
set folderName to ((text items 1 through idx of pathAsList) as text) & ":"
else
set folderName to item idx of pathAsList
end if
set AppleScript's text item delimiters to saveDelim
return folderName
end ParentFromPath
Because Picture format (".pict") is not supported on Lion and newer OS.
You can use the term picture to read a image file (JPEG, PNG, ...), the format will not be in the Picture format , but the original format of the file.
tell application "iTunes"
set v_TrackSelection to selection
if v_TrackSelection is not {} then
repeat with vTrack in v_TrackSelection
set vPictFolder to my (ParentFromPath(location of vTrack as string)) as text
set thisPict to my getpictData(vPictFolder & "folder.jpg")
if thisPict is not "" then
delete artworks of vTrack
set data of artwork 1 of vTrack to (thisPict)
end if
end repeat
else
display dialog ("select tracks first !")
end if
end tell
on getpictData(tFile)
try
return (read (tFile as alias) as picture)
end try
display dialog tFile
return "" -- not exists
end getpictData
Code snippet:
tell application "Finder" to set new_item to ¬
(container of this_item as string) & (name of this_item) & "s"
save this_image in new_item as typ
Its saving the file as filename.pngs I want it to save as filenames.png. Any ideas how to fix this?
Save this as an application, then you can drop things on it and it will copy them adding an s to the name. Or you can double-click it and it will ask you to choose a file to copy. NOTE: change the property appendText if you want to change the text (i.e. "s") that's added to the name.
Notice the handler getName_andExtension(f). That's what I use to get the name and extension from a file. I use that to calculate the new path when adding the s.
I hope that helps!
property appendText : "s"
on run
set f to choose file
duplicateInPlace_appendingText(f, appendText)
end run
on open the_items
repeat with f in the_items
duplicateInPlace_appendingText(f, appendText)
end repeat
end open
on duplicateInPlace_appendingText(f, textToAppend)
set f to f as text
set {nm, ex} to getName_andExtension(f)
tell application "Finder" to set theContainer to (container of item f) as text
if ex is "" then
set new_path to theContainer & nm & textToAppend
else
set new_path to theContainer & nm & textToAppend & "." & ex
end if
do shell script "cp -R " & quoted form of POSIX path of f & space & quoted form of POSIX path of new_path
end duplicateInPlace_appendingText
on getName_andExtension(f)
set f to f as text
set {name:nm, name extension:ex} to info for file f without size
if ex is missing value then set ex to ""
if ex is not "" then
set nm to text 1 thru ((count nm) - (count ex) - 1) of nm
end if
return {nm, ex}
end getName_andExtension
name of this_item gives the full name of the Finder item, including the file extension. You need to split it up. Unfortunately, this isn't as easy as it could be. You could do something like:
tell application "Finder"
get the selection
set {dispname, ext, exthidden} to {displayed name, name extension, extension hidden} of item 1 of the result
end tell
if exthidden then
dispname & "s." & ext
else
((characters 1 through -(2 + (count of ext)) of dispname) as string) & "s." & ext
end if
That just builds the modified name for the first item in the Finder selection, without doing anything with it.