CreateLowRes

From Wurst-Wasser.net
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

This AppleScript automagically creates low res images from high res images in a hot folder.

Please don't complain about formatting - it's hard enough to make this look good in a Wiki.

Download here: File:Createlowres2009-06-30.zip

(* CreateLowRes.scpt (c) by Heiko Kretschmer *)
(* *************************************************************************** *)
(* Globals *)
global gTargetDPI, gLocked, gFolderNameLowRes, gSendReturnMax, gDebugLog, gSearchFolder, gFileLogPOSIXPath, gFileSuffixesToProcess
global gTargetSuffix
#, gSearchPath
# property new_foldername : "TIFF Images"
(* *************************************************************************** *)
(* Functions *)
on main(scanFolderMacOS)
if gLocked is false then
set gLocked to true
tell me to say ("Starting up, checking " & (POSIX path of scanFolderMacOS) as string)
(* Check this folder and its sub-folders *)
scanFolder(scanFolderMacOS)
set gLocked to false (* We're through, unlock *)
else # if locked
tell me to say ("We're locked, so I'm skipping this run.")
end if (* not locked *)
end main
(* create low res file, if low res does not exist, or low res is older than highres *)
on createLowResOfFile(fileHighRes)
(* Create LowRes-Folder *)
set fileHighResPOSIXPath to (POSIX path of fileHighRes)
tell me to say ("fileHighResPOSIXPath: " & fileHighResPOSIXPath)
tell me to set containingFolder to pathOfPOSIXFilepath(fileHighResPOSIXPath) & "/"
set containingFolderAlias to POSIX file containingFolder
tell me to say ("Containing folder: \"" & containingFolder & "\"")
tell application "Finder"
if not (the folder gFolderNameLowRes of folder containingFolderAlias exists) then (* http://applescript.codefetch.com/example/k5/Applescript%20Examples%20CD(converted)/Chapter%205/Page%2090%20-%20Creating%20a%20Folder%20(Only%20if%20Necessary).scpt.txt?qy=if *)
tell me to say ("Creating low-res-folder \"" & gFolderNameLowRes & "\" in \"" & containingFolder & "\"")
make new folder at containingFolderAlias with properties {name:gFolderNameLowRes} (* http://www.macresearch.org/tutorial_applescript_for_scientists_part_i *)
end if
end tell
tell me to set fileName to fileOfPOSIXFilepath(fileHighResPOSIXPath)
tell me to set filenameWithoutSuffix to filenameWithoutSuffix(fileName)
tell me to say ("filenameWithoutSuffix: " & filenameWithoutSuffix)
set lowResFileNameWithoutSuffix to filenameWithoutSuffix (* In our case, the filename of the low-res-image is the same as the original file (except for the suffix) *)
tell me to say ("lowResFileNameWithoutSuffix: " & lowResFileNameWithoutSuffix)
set lowResFileName to lowResFileNameWithoutSuffix & "." & gTargetSuffix
tell me to say ("lowResFileName: " & lowResFileName)
set lowResFolderAlias to POSIX file (containingFolder & gFolderNameLowRes & "/")
tell me to say ("lowResFolderAlias: " & lowResFolderAlias)
set lowResFilePOSIXPath to (POSIX path of lowResFolderAlias) & lowResFileName
tell me to say ("lowResFilePOSIXPath: " & lowResFilePOSIXPath)
(* Check for Low Res file / compare age *)
(* First, check if LowRes-File exists *)
tell application "Finder" to set lowResFileExists to (the file lowResFileName of folder lowResFolderAlias exists)
tell me to say ("lowResFileExists: " & lowResFileExists)
(* Compare file ages *)
# Some bad property, since its language specific: modification date:date "Samstag, 27. Juni 2009 16:36:49 Uhr"
if (lowResFileExists) then
(* if the low res file already exists, compare file age with original file *)
tell me to set ageOfLowRes to ageOfFile(lowResFilePOSIXPath)
tell me to set ageOfHiRes to ageOfFile(fileHighResPOSIXPath)
tell me to say ("ageOfHiRes: " & ageOfHiRes)
tell me to say ("ageOfLowRes: " & ageOfLowRes)
if (ageOfLowRes is greater than ageOfHiRes) then
tell me to say ("Skipping file \"" & fileHighResPOSIXPath & "\", because its low res version has already been created.")
return
end if
end if
(* stop here while debugging *)
# return
(* Create Low Res *)
tell me to say ("Creating low-res version of \"" & fileHighResPOSIXPath & "\"...")
try
with timeout of 10 seconds
tell application "Adobe Photoshop CS3"
(* Open HighRes *)
try
with timeout of 20 seconds
tell application "Adobe Photoshop CS3"
activate
open fileHighRes --as JPEG -- showing dialogs never
#open theImage with options {class:JPEG}
end tell
end timeout
on error number errNum from obj to newClass
#display dialog "Das JPEG is scheisse!" buttons {"Oh, kacke!"}
try</nowiki>
(* Nun solange Returns senden, bis das Ding Ruhe gibt! *)
tell application "System Events"
(* Find the frontmost process *)
set fmp to (every process whose frontmost is true and has scripting terminology is true)
(* Hit return, this saves the ape before your Mac! :) *)
set returnStrokes to 0
repeat with p in (fmp)
(* Ois isi *)
keystroke return
(* Don't get stuck in this repeat. After 4 repetitions -> exit! *)
if returnStrokes is less than gSendReturnMax then
exit repeat
end if
set returnStrokes to returnStrokes + 1
end repeat -- repeat fmp
end tell --system events
end try
end try
</nowiki>
(* Create LowRes *)
duplicate document 1
close document 1
tell document 1
resize image resolution gTargetDPI resample method bicubic
save in file lowResFilePOSIXPath as Photoshop format without copying
close
end tell
tell me to say ("Created low-res version of \"" & fileHighResPOSIXPath & "\". ")
end tell
end timeout
on error
tell me to say ("Error: Failed to create low-res version of \"" & fileHighResPOSIXPath & "\"!")
end try
(* Because it could hang with some error, we'll now kill Adobe PS *)
tell application "Adobe Photoshop CS3" to quit
tell application "Finder" to delay 10
killAdobePhotoshop() (* Just in case Adobe Photoshop *really* hangs *)
end createLowResOfFile
(* get age of a file, see "man stat" *)
on ageOfFile(filepathposix)
set cmd to "stat -f \"%m\" " & "\"" & filepathposix & "\"" (* %m = modfication date *)
tell application "Finder" to set result to do shell script (cmd)
return result
end ageOfFile
(* scan folder for more files and folders *)
on scanFolder(theFolder)
(* scan for sub-folders and files, process them... *)
set folderContents to list folder of theFolder
repeat with oneItem in folderContents
tell me to say ("Found " & "\"" & oneItem & "\"")
set oneFile to (theFolder as string) & contents of oneItem
processFile(alias oneFile)
end repeat
end scanFolder
(* processFile (or folder) *)
on processFile(oneFile)
set theoneFileInfo to info for oneFile
(* Check if this is a dot-file or dot-folder *)
if (name of theoneFileInfo begins with ".") then
(* Dot-File/Folder *)
tell me to say ("Skipping \"" & POSIX path of oneFile & "\", because it begins with a \"" & "." & "\".")
else
(* Kein Dot-File/Folder *)
if folder of theoneFileInfo then
(* Check if this subfolder is a LowRes-Folder. If yes, skip it! Don't want to create low res of low res and get stuck in an infinite loop *)
if (name of theoneFileInfo contains gFolderNameLowRes) then
tell me to say ("Will not descend into folder \"" & POSIX path of oneFile & "\", because it contains \"" & gFolderNameLowRes & "\".")
else
(* Found folder, walk through this folder... *)
scanFolder(oneFile)
end if
else
(* Check whether the file fits our suffix list *)
tell me to set oneFileSuffix to suffixOfFilename(name of theoneFileInfo)
if (gFileSuffixesToProcess contains oneFileSuffix) then
(* valid file, processing this file... *)
createLowResOfFile(oneFile)
else
tell me to say ("Skipping file \"" & POSIX path of oneFile & "\", because it has a bad suffix.")
end if (* suffix OK *)
end if
end if
end processFile
(* Move file to trash *)
on moveToTrash(theFile)
tell application "Finder"
set theFileName to name of theFile
end tell
--display dialog dateiName
tell application "Finder"
activate
select theFile
delete selection
end tell
end moveToTrash
(* get just the suffix of a filename with suffix, e.g. "jpg" of "test.jpg" *)
on suffixOfFilename(fileName)
tell application "Finder"
set s to do shell script "echo \"" & fileName & "\" | cut -d. -f2-" (* this fails if filename contains more than one "."! *)
#log s
end tell
end suffixOfFilename
(* get just the filename of a filename with suffix, e.g. "test" of "test.jpg" *)
on filenameWithoutSuffix(fileName)
tell application "Finder"
set s to do shell script "echo \"" & fileName & "\" | cut -d. -f1"
#log s
end tell
end filenameWithoutSuffix
(* get the file component of a POSIX file path *)
on fileOfPOSIXFilepath(p)
set oldAST to AppleScript's text item delimiters
set AppleScript's text item delimiters to "/"
set elements to text items of p
set AppleScript's text item delimiters to oldAST
set res to last item of elements
return res
end fileOfPOSIXFilepath
(* get the path component of a POSIX file path *)
on pathOfPOSIXFilepath(p) (* http://macscripter.net/viewtopic.php?id=24525 *)
(* Text-Liste in echte Liste umwandeln *)
set oldAST to AppleScript's text item delimiters
set AppleScript's text item delimiters to "/"
set elements to text items of p
(* Letztes Element rauswerfen *)
set elements to items 1 thru ((count of items in elements) - 1) of elements
set res to elements as text
set AppleScript's text item delimiters to oldAST
return res
end pathOfPOSIXFilepath
(* Diese Funktion ersetzt einen String innerhalb eines strings durch einen anderen String. Quelle: http://macscripter.net/viewtopic.php?id=13008*)
to changeSubString of t from s to r
set d to text item delimiters
set text item delimiters to s
set t to t's text items
set text item delimiters to r
tell t to set t to beginning & ({""} & rest)
set text item delimiters to d
t
end changeSubString
</nowiki>
on say (message)
(* Log ins EventLog des AppleScript Editors schreiben *)
log {message}
(* Message ins Log auffe Disk schreiben *)
if gDebugLog is true then
tell application "Finder"
set theLine to (do shell script "date +'%Y-%m-%d %H:%M:%S'" as string) & ": " & (message as string)
do shell script "echo " & "'" & theLine & "'" & " >> " & gFileLogPOSIXPath
end tell
end if
end say
on chomp(stringwithspaces)
set cmd to "echo " & stringwithspaces & " | awk '{printf $1}'"
return (do shell script cmd)
end chomp
(* Den Adobe Crash Reporter (oder mehrere davon) entsorgen *)
on killAdobeCrashReporter()
set app_name to "AdobeCrashReporter"
set the_pids to (do shell script "ps ax | grep " & (quoted form of app_name) & " | grep -v grep | awk '{print $1}' | tr ' ' ' '") (* Der Zeilenvorschub ist kein Tippfehler! Ich tausche hier das Return gegen ein Space, damit Kill mehrere Prozesse killen kann *)
if the_pids is not "" then
try
do shell script ("kill -9 " & the_pids)
on error
tell me to say ("Killing AdobeCrashReporter, pid " & the_pids & " failed.")
end try
end if
end killAdobeCrashReporter
(* Das Adobe Photoshop abwuergen *)
on killAdobePhotoshop()
set app_name to "Adobe Photoshop"
set the_pids to (do shell script "ps ax | grep " & (quoted form of app_name) & " | grep -v grep | awk '{print $1}' | tr ' ' ' '") (* Der Zeilenvorschub ist kein Tippfehler! Ich tausche hier das Return gegen ein Space, damit Kill mehrere Prozesse killen kann *)
if the_pids is not "" then
tell me to say ("Killing " & app_name & "!")
try
tell application "Finder"
(* Da es sein kann, dass ich noch eine pid feststellen konnte, aber ID sich zwischenzeitlich doch gracefully verabschiedet, mache ich das mit einem try (Gefahr, dass das Script sonst stehen bleinbt, weil das kill keinen Process findet) *)
do shell script ("kill -9 " & the_pids)
tell me to say ("Killing " & app_name & ", pid " & the_pids & " succeeded.")
end tell
on error
tell me to say ("ERROR: Killing " & app_name & ", pid " & the_pids & " failed.")
end try
else
tell me to say ("Not killing " & app_name & ", because PID is nil (already quit?).")
end if
(* Tempfiles wegwerfen *)
#nur ID tell me to removeRecoveryFiles()
end killAdobePhotoshop
(* *************************************************************************** *)
(* on run/idle handlers *)
(* when starting up... *)
on run
(* Preferences, feel free to change *)
set gSearchFolder to (POSIX file ((POSIX path of (path to home folder)) & "Desktop/tescht/")) (* use trailing "/"! *)
# set gSearchFolder to (POSIX file ((POSIX path of (path to home folder)) & "Desktop/CreateLowRes/Testfiles/")) (* use trailing "/"! *)
set gTargetDPI to 72
set gFolderNameLowRes to "LowRes"
set gDebugLog to true
set gFileSuffixesToProcess to {"jpg", "jpeg", "psd", "tiff", "tif", "bmp", "eps", "png"}
set gTargetSuffix to "psd"
(* Don't change these: *)
set gLocked to false
set gSendReturnMax to 4
(* If folder does not exist, ask user to choose one *)
tell application "Finder"
if (the gSearchFolder exists) is false then
set gSearchFolder to choose folder with prompt "Choose folder to watch:"
end if
end tell
set gFileLogPOSIXPath to (POSIX path of gSearchFolder) & "CreateLowRes.log"
tell me to say ("Logging: " & gDebugLog & ", Logfile: " & gFileLogPOSIXPath)
tell me to say ("Scanning " & gSearchFolder)
(* Run *)
tell me to say ("Starting...")
main(gSearchFolder)
(* Done *)
tell me to say ("Fin...")
end run
(* Handler, der einfach nur troedelt, bis das Script wieder laufen soll. *)
on idle
(* Run *)
tell me to say ("Starting...")
main(gSearchFolder)
(* Done *)
tell me to say ("Fin...")
(* erst spaeter nochmal in diesen Handler reinschaun. *)
return 300 (* Angabe in Sekunden *)
end idle