Image Scaling & Saving Automation

Hi folks.

I want to write a Droplet that saves scaled images into their own folders. For instance, I get a 2048 x 1700 image called “watermelon.jpg”. I want to create a folder called “watermelon Æ’” and inside it make the following images:

watermelon 100.jpg
watermelon 200.jpg
watermelon 300.jpg
watermelon 500.jpg

watermelon 100.png
watermelon 200.png
watermelon 300.png
watermelon 400.png
watermelon 500.png

watermelon.jpg (original file moved from the convert folder)

All images go into the convert folder, so each image that’s in there, has its own folder created and images exported to scaled sizes, and the original moved into that folder.

Any advice? I can’t even get a list of files inside a folder at the moment.

Cheers

This is very basic droplet code to get you started. Open it into Script Editor, and then Export it as an application. Drop a folder on it, and you will see where you can go from there.


on open dropping
	set file_count to 0
	repeat with eachDropped in dropping
		if folder of (info for eachDropped) then
			my countFiles(eachDropped)
		end if
	end repeat
end open

to countFiles(dFolder)
	tell application "Finder"
		set allFiles to every file of dFolder
		display dialog "You dropped a folder entitled " & (dFolder's name as text) & " that contains " & ((allFiles's length) as text) & " files"
		set fileNames to ""
		repeat with eachFile in allFiles
			set fileNames to fileNames & (eachFile's name as text) & return
		end repeat
		display dialog "Here are the file Names:" & return & return & fileNames
	end tell
	
end countFiles

on run
	display dialog "Drop a folder here, and it will count and then list the files"
end run

Good Luck,

Hello.

Here is something that might get you going with image events and scaling. I have actually written a whole suit of image manipulation scripts, but it has been put on hold for a while.

Drop the ImgEvents script into the ~/Library/Script Libraries folder, and try the Scale Image script. You may be able to scavenge it for scaling operations in your droplet, which Craig has provided the skeleton for. :slight_smile:

(The script below doesn’t alter the original image.)

ImgEvents.scpt

use AppleScript version "2.3"
use scripting additions
-- This script requires Mavericks or newer, but can be retrofitted as 
-- a "vanilla" script object.
-- Drop this script into your "/Users/You/Library/Script Libraries" 
-- folder. Create it if it doesn't exist.

-- http://www.macosxautomation.com/applescript/imageevents/04.html
-- Should get you started with image events.
-- Copyright © 2015  McUsr parts copyright © 2015 or earlier MacOsXAutomation, you are free to use, and share per email, but not to publish on a webpage.
# http://macscripter.net/viewtopic.php?pid=180878#p180878
#  Thanks to Nigel Garvey for advice, testing and suggestions.
property openTypes : {"PDF", "com.adobe.pdf", "BMP", "com.microsoft.bmp", "JPEG", "JPEG2", "jpg", "public.jpeg", ¬
	"PICT", "com.apple.pict", "PNG", "public.png", "PSD", "com.adobe.photoshop-image", "TIFF", "public.tiff", "com.compuserve.gif", "QuickTime Image"}

property saveFormats : {"jpeg", "jp2", "tiff", "bmp", "psd"}
-- those are formats, as coerced to string by Image Events, they should work equally well with sips.

-- jpeg | tiff | png | jp2 | bmp | qtif | psd | sgi | tga
property quitDelay : 600

property blackColor : {0, 0, 0}

-- From aRounderRound, by Nigel Garvey. (Who else? :) )
-- Round to nearest integer (rounding 0.5 away from zero).
on rnd(n)
	return n div 0.5 - n div 1
end rnd


on getImageFile against scriptTitle
	tell application id "MACS" -- Telling finder quickly!
		if selection is not {} then
			set this_item to selection as text
		else
			set this_item to null
		end if
	end tell
	if this_item is not null then
		tell application id "sevs"
			if class of item this_item is not folder then
				set finfo to properties of item this_item
				set ftype to type identifier of finfo
			else
				set this_item to null
			end if
		end tell
	end if
	if this_item is not null and ftype is not in my openTypes then set this_item to null
	if this_item is null then
		try
			tell application (path to frontmost application as text)
				-- no timeout for choose file dialog
				set this_item to (choose file with prompt scriptTitle & ":
Select an imagefile to process: " of type my openTypes without invisibles) as text
			end tell
			
		on error e number n
			return null
		end try
	end if
	return this_item
end getImageFile

on chooseImageFile by the_item against scriptTitle beside theSubTitle
	tell application id "sevs"
		set theF to path of container of item (the_item as text) as alias
	end tell
	try
		tell application (path to frontmost application as text)
			set new_item to (choose file of type (openTypes of my img) default location theF with prompt theSubTitle & " of: " & scriptTitle & ":
Choose a different image file to operate on." without invisibles) as text
		end tell
	on error
		return null
	end try
	return new_item
end chooseImageFile

to showProcessInfo for someInfo against scriptTitle beside theSubTitle
	tell application (path to frontmost application as text)
		display dialog theSubTitle & ": 

" & someInfo with title scriptTitle buttons {"Ok"} default button 1 giving up after ((my quitDelay) - 1)
	end tell
end showProcessInfo

to chooseNewSaveFormat for theCurrentFormat by quitDelay against scriptTitle beside theSubTitle
	-- this handler is to be invoked from within image events
	-- but should work equally well on the outside.
	
	try
		tell application (path to frontmost application as text)
			display dialog theSubTitle & ":
I can't save an Image with the " & theCurrentFormat & " format" with title scriptTitle with icon caution buttons {"Cancel", "Choose other image format"} cancel button 1 default button 2 giving up after (quitDelay - 1)
		end tell
		
		if gave up of result then
			return null
		end if
	on error
		return null
	end try
	set timeOutError to false
	try
		with timeout of (quitDelay - 1) seconds
			tell application (path to frontmost application as text)
				set imageType to choose from list my saveFormats default items item 1 of my saveFormats with title scriptTitle with prompt theSubTitle & ":
Choose a format we can save the altered Image to:"
			end tell
		end timeout
	on error
		set timeOutError to true
	end try
	if timeOutError then
		try
			tell application id "sevs"
				set firstProcessName to name of first process whose frontmost is true and visible is true
				click button 1 of window 1 of process firstProcessName
			end tell
			-- we timed  out
			return null
		on error e number n
			tell application (path to frontmost application as text)
				display alert scriptTitle & ":
You'll need to add the app " & firstProcessName & " to the apps, that are entitled to be using UIScripting, in order for this script to exit more gracefully when you have left the computer." giving up after 86400
			end tell
			return null
		end try
	else if imageType is false then
		return null
	else
		return item 1 of imageType
	end if
end chooseNewSaveFormat


to chooseCommand from commandList about commandIndex by quitDelay against scriptTitle
	-- this is the main dispatcher, it breaks the pattern of returning null upon error
	-- since null is used in main, to keep us in the loop, whereas false makes us exit.
	
	set timeOutError to false
	try
		with timeout of (quitDelay - 1) seconds
			tell application (path to frontmost application as text)
				set choice to choose from list commandList default items item commandIndex of commandList with title scriptTitle with prompt "Choose a Command"
			end tell
		end timeout
	on error
		set timeOutError to true
	end try
	if timeOutError then
		try
			tell application id "sevs"
				set firstProcessName to name of first process whose frontmost is true and visible is true
				click button 1 of window 1 of process firstProcessName
			end tell
			-- we timed  out
			return false
		on error e number n
			tell application (path to frontmost application as text)
				display alert scriptTitle & ":
You'll need to add the app " & firstProcessName & " to the apps, that are entitled to be using UIScripting in the Privacy Preferences Pane, in order for this script to exit more gracefully when you have left the computer." & e & return & ":" & n giving up after 86400
			end tell
			return false
		end try
	else if choice is false then
		return choice
	else
		return item 1 of choice
	end if
end chooseCommand


on ddWthoutColor about theAnswer by aMessage against scriptTitle beside theSubTitle
	tell application (path to frontmost application as text)
		display dialog theSubTitle & ":
" & aMessage default answer theAnswer with title scriptTitle default button 2 cancel button 1 with icon caution giving up after ((my quitDelay) - 1)
	end tell
	return result
end ddWthoutColor

on ddColorChoice about theAnswer by aMessage against scriptTitle beside theSubTitle
	tell application (path to frontmost application as text)
		display dialog theSubTitle & ":
" & aMessage default answer theAnswer with title scriptTitle buttons {"Cancel", "Set Color", "Continue"} cancel button 1 default button 3 with icon 1 giving up after ((my quitDelay) - 1)
	end tell
	return result
end ddColorChoice

on showErrMsg by errMessage at errNr against scriptTitle beside theSubTitle
	tell application (path to frontmost application as text)
		display dialog theSubTitle & ":
" & errMessage & " : " & errNr with title scriptTitle buttons {"Ok"} default button 1 with icon caution giving up after ((my quitDelay) - 1)
	end tell
end showErrMsg

on simpleDialog by aMessage against scriptTitle beside theSubTitle
	tell application (path to frontmost application as text)
		display dialog theSubTitle & ":
" & aMessage with title scriptTitle buttons {"Ok"} default button 1 with icon caution giving up after ((my quitDelay) - 1)
	end tell
end simpleDialog

using terms from application "Image Events"
	
	on presentFType(theFtype)
		if theFtype is BMP then
			return "BMP"
		else if theFtype is GIF then
			return "GIF"
		else if theFtype is JPEG then
			return "JPEG"
		else if theFtype is JPEG2 then
			return "JPEG2"
		else if theFtype is MacPaint then
			return "MacPaint"
		else if theFtype is PDF then
			return "PDF"
		else if theFtype is Photoshop then
			return "Photoshop"
		else if theFtype is PICT then
			return "PICT"
		else if theFtype is PNG then
			return "PNG"
		else if theFtype is PSD then
			return "PSD"
		else if theFtype is QuickTime Image then
			return "QuickTime Image"
		else if theFtype is image then
			return "Image"
		else if theFtype is SGI then
			return "SGI"
		else if theFtype is text then
			return "Text"
		else if theFtype is TGA then
			return "TGA"
		else if theFtype is TIFF then
			return "TIFF"
		end if
	end presentFType
	
	on getFType(theFtype)
		if theFtype is "BMP" then
			return BMP
		else if theFtype is "GIF" then
			return GIF
		else if theFtype is "JPEG" then
			return JPEG
		else if theFtype is "JPEG2" then
			return JPEG2
		else if theFtype is "MacPaint" then
			return MacPaint
		else if theFtype is "PDF" then
			return PDF
		else if theFtype is "Photoshop" then
			return Photoshop
		else if theFtype is "PICT" then
			return PICT
		else if theFtype is "PNG" then
			return PNG
		else if theFtype is "PSD" then
			return PSD
		else if theFtype is "QuickTime Image" then
			return QuickTime Image
		else if theFtype is "image" then
			return image
		else if theFtype is "SGI" then
			return SGI
		else if theFtype is "text" then
			return text
		else if theFtype is "TGA" then
			return TGA
		else if theFtype is "TIFF" then
			return TIFF
		end if
	end getFType
	
	on presentBitDepth(theBitDepth)
		
		if theBitDepth is best then
			return "Best"
		else if theBitDepth is black & white then
			return "Black & White"
		else if theBitDepth is color then
			return "Color"
		else if theBitDepth is four colors then
			return "Four Colors	"
		else if theBitDepth is four grays then
			return "Four Grays"
		else if theBitDepth is grayscale then
			return "Grayscale"
		else if theBitDepth is millions of colors then
			return "Millions of Colors"
		else if theBitDepth is millions of colors plus then
			return "Millions of Colors Plus"
		else if theBitDepth is sixteen colors then
			return "Sixteen Colors"
		else if theBitDepth is sixteen grays then
			return "Sixteen Grays"
		else if theBitDepth is thousands of colors then
			return "Thousands of Colors"
		else if theBitDepth is two hundred fifty six colors then
			return "Two hundred fifty six Color"
		else if theBitDepth is two hundred fifty six grays then
			return "Two hundred fifty six Grays"
		end if
	end presentBitDepth
	
	
	on presentColorSpace(theColorSpace)
		if theColorSpace is CMYK then
			return "CMYK"
		else if theColorSpace is Eight channel then
			return "Eight channel"
		else if theColorSpace is Eight color then
			return "Eight color"
		else if theColorSpace is Five channel then
			return "Five channel"
		else if theColorSpace is Five color then
			return "Five color"
		else if theColorSpace is Gray then
			return "Gray"
		else if theColorSpace is Lab then
			return "Lab"
		else if theColorSpace is named then
			return "Named"
		else if theColorSpace is RGB then
			return "RGB"
		else if theColorSpace is Seven channel then
			return "Seven channel"
		else if theColorSpace is Seven color then
			return "Seven color"
		else if theColorSpace is Six channel then
			return "Six channel"
		else if theColorSpace is Six color then
			return "Six color"
		else if theColorSpace is XYZ then
			return "XYZ"
		end if
	end presentColorSpace
end using terms from

to showImageInfo for this_item against scriptTitle beside theSubTitle
	-- http://www.macosxautomation.com/applescript/imageevents/01.html
	-- Todo, skrive en melding om at vi ikke kan bearbeide et image i dette formatet, hvis så.
	-- Men at vi kan konvertere til et annet format vi kan lagre til.
	try
		tell application id "com.apple.imageevents"
			-- start the Image Events application
			launch
			set quit delay to 60
			-- open the image file
			set this_image to open this_item
			-- 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 theSubTitle & ":" & return & return
			set the image_info to the image_info & ¬
				"Name: \"" & (name of props_rec) & "\"" & return
			--	set the image_info to the image_info & ¬
			"File: \"" & (POSIX path of image file of props_rec) & "\"" & return
			set the image_info to the image_info & ¬
				"Location: \"" & (POSIX path of location of props_rec) & "\"" & return
			set ImageFormat to my presentFType(file type of props_rec)
			set the image_info to the image_info & ¬
				"File Type: " & ImageFormat
			if ImageFormat is not in my saveFormats then set image_info to the image_info & return & "-> This Image will be converted to another format in order to perform any altering operations on it."
			set image_info to image_info & return
			set the image_info to the image_info & ¬
				"Bit Depth: " & my presentBitDepth(bit depth of props_rec) & return
			set the image_info to the image_info & ¬
				"Color Space: " & my presentColorSpace(color space of props_rec) & return
			copy (resolution of props_rec) to {hres, vres}
			set hres to my rnd(hres)
			set vres to my rnd(vres)
			set the image_info to the image_info & ¬
				"Resolution: (" & hres & ", " & vres & ") Dots per Inch (Dpi)" & return
			set the image_info to the image_info & "Points per Inch: " & (72.0 as string) & return
			copy (dimensions of props_rec) to {x, y}
			set the image_info to the image_info & "Dimensions: (width, height)" & return
			set the image_info to the image_info & ¬
				" Pixels: " & (my rnd(x)) & ", " & (my rnd(y)) & return
			set wPoints to my rnd(x / (hres / 72))
			set hPoints to my rnd(y / (vres / 72))
			set the image_info to the image_info & ¬
				" Points: " & wPoints & ", " & hPoints & return
			set wInch to my rnd(wPoints / 72.0)
			set hInch to my rnd(hPoints / 72.0)
			set the image_info to the image_info & ¬
				"Inches: " & wInch & ", " & hInch & return
			set the image_info to the image_info & ¬
				"     Cm: " & (my rnd(wInch * 2.54)) & ", " & (my rnd(hInch * 2.54))
			
		end tell
		tell application (path to frontmost application as text)
			try
				display dialog image_info with title scriptTitle buttons {"Clipboard", "Quick Look", "Ok"} cancel button 3 default button 2 with icon 1 giving up after ((my quitDelay) - 1)
			on error
				return null
			end try
		end tell
		if not gave up of result then
			set btn to button returned of result
		else
			return null
		end if
		if btn = "Clipboard" then
			set the clipboard to image_info
		else if btn = "Quick Look" then
			tell application id "sevs" to set pxPath to POSIX path of item this_item
			do shell script "qlmanage -p " & quoted form of pxPath & " & >/dev/null 2>&1 "
		end if
	on error errMessage number errNr
		showErrMsg by errMessage at errNr against scriptTitle beside theSubTitle
		return null
	end try
	return true
end showImageInfo

on getImageDimensions for the_item against scriptTitle beside theSubTitle
	try
		tell application id "com.apple.imageevents"
			-- start the Image Events application
			launch
			set quit delay to 60
			-- open the image file
			set this_image to open the_item
			copy dimensions of this_image to {W, H}
			close this_image
		end tell
		return {W, H}
	on error errMessage number errNr
		showErrMsg of img by errMessage at errNr against scriptTitle beside theSubTitle
		return null
	end try
end getImageDimensions

on preparePointValues from resultList
	set _origW to rnd(item 1 of resultList)
	set _origH to rnd(item 2 of resultList)
	set startValue to "" & _origW & "," & _origH
	return {_origW, _origH, startValue}
end preparePointValues

on calculatePointValues from imgDimsAndRes
	
	set points_per_inch to 12
	set pixels_per_point to (item 3 of imgDimsAndRes) / points_per_inch
	-- we calculate the image size in points when we deal with points.
	set w_points to rnd((item 1 of imgDimsAndRes) / pixels_per_point)
	set h_points to rnd((item 2 of imgDimsAndRes) / pixels_per_point)
	return {w_points, h_points, pixels_per_point}
end calculatePointValues

on performPaddingOfImageByPixelDimensions for the_item by wantedValues over hex_color against scriptTitle beside theSubTitle
	try
		tell application id "com.apple.imageevents"
			launch
			set quit delay to my quitDelay
			-- open the image file
			set this_image to open the_item
			-- check if padding is doable on this item
			copy file type of this_image to ImageFormat
			set ImageFormat to my presentFType(ImageFormat)
			if ImageFormat is not in my saveFormats then
				set canUseOriginalSaveFormat to false
			else
				set canUseOriginalSaveFormat to true
			end if
			if not canUseOriginalSaveFormat then
				set newFormat to chooseNewSaveFormat of me for ImageFormat by my quitDelay against scriptTitle beside theSubTitle
				if newFormat is null then
					try
						-- purge the open image data
						close this_image
						-- for the case that the user left the comp, so image events quit on us!
						-- set back the quit after idle delay
						set quit delay to 60
					end try
					return null -- The user declined the operation
				end if
			end if
			-- set back the quit after idle delay
			set quit delay to 60
			-- Save a copy of the original image, new format, or not
			if not canUseOriginalSaveFormat then
				copy my derive_filename((the_item as alias), newFormat, "-", "") to {new_name, target_HFSpath}
				save this_image as my getFType(newFormat) in file target_HFSpath
			else
				-- derive new name for the new image file
				copy my derive_filename((the_item as alias), "", "-", "") to {new_name, target_HFSpath}
				save this_image in file target_HFSpath with icon
			end if
			-- purge the open image data
			close this_image
			
			if item 1 of wantedValues is my blackColor then
				-- perform the action with image events!
				set new_image to open target_HFSpath
				pad this_image to dimensions (item 2 of wantedValues)
				-- save the changes
				set the new_image to save this_image in file target_HFSpath with icon
				-- purge the open image data
				close new_image
			end if
		end tell
	on error errMessage number errNr
		showErrMsg by errMessage at errNr against scriptTitle beside theSubTitle
		return null
	end try
	
	if item 1 of wantedValues is not my blackColor then -- Not Black
		set in_path to quoted form of POSIX path of (the_item as alias)
		-- set out_path to quoted form of POSIX path of (target_HFSpath as alias)
		set out_path to quoted form of posixPathOfAnytingAsText(target_HFSpath)
		if not canUseOriginalSaveFormat then set in_path to out_path
		-- we have already started to use out path!
		set target_W to (item 1 of (item 2 of wantedValues)) as string
		set target_H to (item 2 of (item 2 of wantedValues)) as string
		-- The with pad color parameter is not working in 10.5.5 so use the SIPS command-line utitlity instead
		do shell script "/usr/bin/sips " & in_path & " -p " & target_H & space & target_W & space & "--padColor " & hex_color & space & "-i --out " & out_path & " >/dev/null 2>&1 & "
	end if
	return target_HFSpath
end performPaddingOfImageByPixelDimensions


on lookAtEndResult for aHfSPath against scriptTitle beside theSubTitle
	-- A kind of stepsaver 
	set firstStep to false
	do shell script "/usr/bin/open -b \"com.apple.finder\" >/dev/null 2>&1 &"
	tell application id "MACS"
		repeat
			try
				set curContainer to container of file aHfSPath as text
				tell Finder window 1
					set target of it to curContainer
					
				end tell
				select file aHfSPath
				exit repeat
			on error
				delay 0.4
			end try
		end repeat
		display dialog theSubTitle & ":
Load the image into Preview, or watch it with QuickLook?" with title scriptTitle buttons {"Cancel", "Preview", "Quick Look"} cancel button 1 default button 2 with icon 1 giving up after my quitDelay
	end tell
	if not gave up of result then
		if button returned of result is "Quick Look" then
			tell application id "sevs" to set pxPath to POSIX path of item aHfSPath
			do shell script "qlmanage -p " & quoted form of pxPath & ">/dev/null 2>&1 &"
		else
			tell application "Preview" to open file aHfSPath
			do shell script "/usr/bin/open -b \"com.apple.Preview\" >/dev/null 2>&1 &"
		end if
	end if
end lookAtEndResult

on continueInPreview for aHfSPath against scriptTitle beside theSubTitle
	notify about "Quitting the script as we open the Image in Preview" against scriptTitle beside theSubTitle
	tell application "Preview" to open file aHfSPath
	do shell script "/usr/bin/open -b \"com.apple.Preview\" >/dev/null 2>&1 &"
end continueInPreview

on notify about theNotification against scriptTitle beside theSubTitle
	tell application (path to frontmost application as text)
		display notification theNotification with title scriptTitle subtitle theSubTitle
	end tell
end notify

on displayResultsNotification for theOperation at endValues against scriptTitle beside theSubTitle
	notify about "Image " & theOperation & " to w:" & (rnd(item 1 of endValues)) & ",h:" & (rnd(item 2 of endValues)) & " px." against scriptTitle beside theSubTitle
end displayResultsNotification


-- Below are handers, and properties for setting and retrieving contents of the cache path
property colorCacheName : "ImageManipulation"
property colorCache : missing value

on loadColorFromScriptCache()
	set cachePath to ((path to library folder from user domain as text) & "caches:" & "net.mcusr." & my colorCacheName)
	local script_cache
	try
		set my colorCache to load script alias cachePath
	on error
		script newScriptCache
			property last_color : my blackColor
		end script
		
		set my colorCache to newScriptCache
	end try
	return last_color of my colorCache
end loadColorFromScriptCache

to saveColorToScriptCache(theColor)
	set cachePath to ((path to library folder from user domain as text) & "caches:" & "net.mcusr." & my colorCacheName)
	set last_color of my colorCache to theColor
	store script my colorCache in cachePath replacing yes
end saveColorToScriptCache

on getColor()
	set the last_color to loadColorFromScriptCache()
	tell application (path to frontmost application as text)
		try
			set chosen_color to choose color default color last_color
		on error e number n
			log "getColor: error during choose " & e & " : " & n
			return null
			-- when we return null, that indicates that we cancelled something
			-- this should bring us right back to the input dialog
		end try
	end tell
	if chosen_color is not last_color then saveColorToScriptCache(chosen_color)
	return chosen_color
end getColor

on RBG_to_HTML(RGB_values)
	-- NOTE: this sub-routine expects the RBG values to be from 0 to 65535
	set the hex_list to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}
	set the the hex_value to ""
	repeat with i from 1 to the count of the RGB_values
		set this_value to (item i of the RGB_values) div 256
		if this_value is 256 then set this_value to 255
		set x to item ((this_value div 16) + 1) of the hex_list
		set y to item (((this_value / 16 mod 1) * 16) + 1) of the hex_list
		set the hex_value to (the hex_value & x & y) as string
	end repeat
	return ("#" & the hex_value) as string
end RBG_to_HTML


-- *-*-

on posixPathOfAnytingAsText(anyFileOrFolderPath)
	-- returns the full posix pathname of anything if the files exists
	local tids, theFile, lastItem, tidsToUse, singleQuoteCheck -- Thanks to Yvan Koenig :)
	set singleQuoteCheck to false
	set tidsToUse to ":"
	try
		(get class of anyFileOrFolderPath)
	on error number -1728 -- it was a filereference
		set anyFileOrFolderPath to POSIX path of (anyFileOrFolderPath as alias) as text
		return anyFileOrFolderPath
	end try
	
	set anyFileOrFolderPath to "" & anyFileOrFolderPath -- doesn't harm.
	if anyFileOrFolderPath starts with "'" and anyFileOrFolderPath ends with "'" then
		set anyFileOrFolderPath to text 2 thru -2 of anyFileOrFolderPath
		set singleQuoteCheck to true
	end if
	if anyFileOrFolderPath starts with "/" and singleQuteCheck is false then
		return anyFileOrFolderPath
	else if anyFileOrFolderPath starts with "/" or anyFileOrFolderPath starts with "~" then
		set tidsToUse to "/"
	end if
	
	set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, tidsToUse}
	set anyFileOrFolderPath to text items of anyFileOrFolderPath as text
	if singleQuoteCheck is true then
		set AppleScript's text item delimiters to "'\\''"
		set anyFileOrFolderPath to text items of anyFileOrFolderPath -- as list
		set AppleScript's text item delimiters to "'"
	end if
	set anyFileOrFolderPath to "" & anyFileOrFolderPath
	set AppleScript's text item delimiters to tidsToUse
	
	if tidsToUse is ":" then
		-- the first item isn' like disk nr 1 then we have to do something.
		if text item 1 of anyFileOrFolderPath is not item 1 of (list disks) then
			set anyFileOrFolderPath to {"Volumes"} & text items of anyFileOrFolderPath
		else
			set anyFileOrFolderPath to {""} & text items 2 thru -1 of anyFileOrFolderPath
		end if
		set AppleScript's text item delimiters to "/"
	else if text item 1 of anyFileOrFolderPath is "~" then
		-- mus get the posix path as text
		set anyFileOrFolderPath to text items 2 thru -2 of (POSIX path of (path to home folder) as text) & text items 2 thru -1 of anyFileOrFolderPath
	end if
	set anyFileOrFolderPath to "" & anyFileOrFolderPath
	set AppleScript's text item delimiters to tids
	return anyFileOrFolderPath
end posixPathOfAnytingAsText

to getPxPath from hfsPath
	tell application id "sevs" to return POSIX path of item hfsPath
end getPxPath

on derive_filename(this_item, new_extension, increment_separator, target_folder)
	-- http://www.macosxautomation.com/applescript/imageevents/08.html
	(*	
a  subroutine  used for deriving the name and path of a new
file using the name of an existing file Pass in file ref  in
alias  format,  the new name extension, an increment separa
tor, and any target directory (in alias format) Name and HFS
path for new file are returned. The name is incremented if a
file exists in the target location. Pass a null  string  for
the target directory to use the item's parent directory Pass
a null string for the new name extension to use  the  item's
current name extension
*)
	-- Denne virker ikke helt fint, må gjøre den om et lite granne. -kanskje.
	tell application id "MACS"
		if target_folder is "" then
			set the target_folder to the container of this_item
		end if
		set the file_name to the name of this_item
		set file_extension to the name extension of this_item
		if the file_extension is "" then
			set the trimmed_name to the file_name
			set extension_separator to ""
		else
			set the trimmed_name to text 1 thru -((length of file_extension) + 2) of the file_name
			set extension_separator to "."
		end if
		if the new_extension is "" then
			set target_name to file_name
			set target_extension to file_extension
		else
			set target_extension to new_extension
			set target_name to (the trimmed_name & extension_separator & target_extension) as Unicode text
		end if
		if (exists document file target_name of target_folder) then
			set the name_increment to 1
			repeat
				set the new_name to (the trimmed_name & increment_separator & (name_increment as Unicode text) & extension_separator & target_extension) as Unicode text
				if not (exists document file new_name of the target_folder) then
					set the target_HFSpath to ((target_folder as Unicode text) & new_name)
					return {new_name, target_HFSpath}
				else
					set the name_increment to the name_increment + 1
				end if
			end repeat
		else
			set the target_HFSpath to ((target_folder as Unicode text) & target_name)
			return {target_name, target_HFSpath}
		end if
	end tell
end derive_filename

Scale Image.scpt

-- http://www.macosxautomation.com/applescript/imageevents/04.html
-- Copyright © 2015  McUsr parts copyright © 2015 or earlier MacOsXAutomation, you are free to use, and share per email, but not to publish on a webpage.
# http://macscripter.net/viewtopic.php?pid=180878#p180878
#  Thanks to Nigel Garvey for advice, testing and suggestions.
property scripttitle : "Scale Images"
use AppleScript version "2.3"
use scripting additions
use img : script "ImgEvents"
property showSomeHelp : "1.  About Scaling an Image"
property showCurInfo : "2.  Show Info of Current Image"
property chooseDifferentImage : "3.  Choose a different Image"
property continueInPreview : "4.  Continue with the Image in Preview"
property scaleLargestSide : "5.  Scale Largest side of Image"
property scaleSmallestSide : "6.  Scale Smallest side of Image"
property scaleChooseSide : "7.  Scale Chosen side of Image"
property scaleByPercentage : "8.  Scale Image by percentage"
property scaleByFactor : "9.  Scale Image by factor"
property scaleImageUp : "10. Scale Image Up Proportionally"
property scaleImageDown : "11. Scale Image Down Proportionally"
property commandList : {showSomeHelp, showCurInfo, chooseDifferentImage, continueInPreview, scaleLargestSide, scaleSmallestSide, scaleChooseSide, scaleByPercentage, scaleByFactor, scaleImageUp, scaleImageDown}
property scalingInfo : "Scaling an image will proportionally increase or decrease the dimensions of an image.

The scaling process will not change the resolution of an image. In other words, an image with a resolution of 72 DPI, scaled to 50% of its current dimensions, will still have a resolution of 72 DPI. An image with a resolution of 300 DPI, scaled to 200% of its current dimensions, will still have a resolution of 300 DPI. source: MacOsXAutomation.

The scaling up command, scales the smallest side to the size of the largest side without further ado, it is inteded to be used after having cropped an image.

The scale down command scales the largest side to the size of the smallest side without further ado, keeping the proportions, it is intended to be used after having padded an image.

The result will be written to a new file."


on run
	set this_item to getImageFile of img against scripttitle
	if this_item is not null then
		script scaleImages
			
			on performScalingByFactor for the_item against scalingFactor by scripttitle beside theSubTitle
				try
					tell application id "com.apple.imageevents"
						launch
						set quit delay to my img's quitDelay
						-- open the image file
						set this_image to open the_item
						-- check if scaling is doable on this item
						copy file type of this_image to ImageFormat
						set ImageFormat to my img's presentFType(ImageFormat)
						if ImageFormat is not in my img's saveFormats then
							set canUseOriginalSaveFormat to false
						else
							set canUseOriginalSaveFormat to true
						end if
						if not canUseOriginalSaveFormat then
							set newFormat to chooseNewSaveFormat of (my img) for ImageFormat by my img's quitDelay against scripttitle beside theSubTitle
							if newFormat is null then
								try
									-- purge the open image data
									close this_image
									-- for the case that the user left the comp, so image events quit on us!
									-- set back the quit after idle delay
									set quit delay to 60
								end try
								return null -- The user declined the operation
							end if
						end if
						-- set back the quit after idle delay
						set quit delay to 60
						-- Save a copy of the original image, new format, or not
						-- Speed over short code, we do the scaling as fast we can, if the original format
						-- is ok.
						if not canUseOriginalSaveFormat then
							copy my img's derive_filename((the_item as alias), newFormat, "-", "") to {new_name, target_HFSpath}
							save this_image as my img's getFType(newFormat) in file target_HFSpath
							-- purge the open image data
							close this_image
							set new_image to open target_HFSpath
							-- perform action
							scale new_image by factor scalingFactor
							-- save the changes
							save new_image with icon
							-- purge the open image data
							close new_image
						else
							-- derive new name for the new image file
							copy my img's derive_filename((the_item as alias), "", "-", "") to {new_name, target_HFSpath}
							scale this_image by factor scalingFactor
							-- save the changes
							save this_image in file target_HFSpath with icon
							-- purge the open image data
							close this_image
						end if
						
					end tell
					notify of img about "The Image is scaled to a factor of " & scalingFactor & "." against scripttitle beside theSubTitle
					return target_HFSpath
				on error errMessage number errNr
					showErrMsg of img by errMessage at errNr against scripttitle beside theSubTitle
					return null
				end try
			end performScalingByFactor
			
			
			
			on performScalingBySize for the_item by newSize at whatSide against scripttitle beside theSubTitle
				try
					tell application id "com.apple.imageevents"
						launch
						set quit delay to my img's quitDelay
						-- open the image file
						set this_image to open the_item
						-- check if scaling is doable on this item
						copy file type of this_image to ImageFormat
						set ImageFormat to my img's presentFType(ImageFormat)
						if ImageFormat is not in my img's saveFormats then
							set canUseOriginalSaveFormat to false
						else
							set canUseOriginalSaveFormat to true
						end if
						if not canUseOriginalSaveFormat then
							set newFormat to chooseNewSaveFormat of (my img) for ImageFormat by my img's quitDelay against scripttitle beside theSubTitle
							if newFormat is null then
								try
									-- purge the open image data
									close this_image
									-- for the case that the user left the comp, so image events quit on us!
									-- set back the quit after idle delay
									set quit delay to 60
								end try
								return null -- The user declined the operation
							end if
						end if
						-- set back the quit after idle delay
						set quit delay to 60
						-- Save a copy of the original image, new format, or not
						-- Speed over short code, we do the scaling as fast we can, if the original format
						-- is ok.
						if not canUseOriginalSaveFormat then
							copy my img's derive_filename((the_item as alias), newFormat, "-", "") to {new_name, target_HFSpath}
							save this_image as my img's getFType(newFormat) in file target_HFSpath
							-- purge the open image data
							close this_image
							set new_image to open target_HFSpath
							-- perform action
							scale new_image to size newSize
							-- save the changes
							-- save this_image with icon
							save new_image with icon
							-- purge the open image data
							close new_image
						else
							-- derive new name for the new image file
							copy my img's derive_filename((the_item as alias), "", "-", "") to {new_name, target_HFSpath}
							scale this_image to size newSize
							-- save the changes
							-- save this_image with icon
							save this_image in file target_HFSpath with icon
							-- purge the open image data
							close this_image
						end if
						
					end tell
					notify of img about whatSide & " side scaled to " & newSize & " px." against scripttitle beside theSubTitle --"Scale Images Scale largest side"
					return target_HFSpath
				on error errMessage number errNr
					showErrMsg of img by errMessage at errNr against scripttitle beside theSubTitle
					return null
				end try
			end performScalingBySize
			(*
			TODO:
			Jeg kan faktorisere performScaling handlerene til en handler, ved å skille ut notify fra disse, og så 
			heller ha et parameter som angir by factor eller size 
			*)
			on queryForSizeOfImage for whichSide against resultList from scripttitle beside theSubTitle
				repeat
					try
						ddWthoutColor of img about "600" by "Set new size for " & whichSide & " of the image(w:" & item 1 of resultList & ", h: " & item 2 of resultList & "),  in pixels." against scripttitle beside theSubTitle
						copy the result to {text returned:newSize, gave up:gaveUp}
						if gaveUp then return null
						set newSize to newSize as integer
						exit repeat
					on error e number n
						if n ≠ -128 then
							beep
						else
							return null
						end if
					end try
				end repeat
				return newSize
			end queryForSizeOfImage
			
			on scaleLargestSide for the_item against scripttitle beside theSubTitle
				set resultList to getImageDimensions of img for the_item against scripttitle beside theSubTitle
				if the resultList is null then return null
				set newLargestSide to queryForSizeOfImage for "largest" against resultList from scripttitle beside theSubTitle
				set target_HFSpath to performScalingBySize for the_item by newLargestSide at "Largest" against scripttitle beside theSubTitle
				return target_HFSpath
			end scaleLargestSide
			
			on scaleSmallestSide for the_item against scripttitle beside theSubTitle
				set resultList to getImageDimensions of img for the_item against scripttitle beside theSubTitle
				if the resultList is null then return null
				set newSmallestSide to queryForSizeOfImage for "smallest" against resultList from scripttitle beside theSubTitle
				set target_HFSpath to performScalingBySize for the_item by newSmallestSide at "Smallest" against scripttitle beside theSubTitle
				return target_HFSpath
			end scaleSmallestSide
			
			on chooseSizeForHeightOrWidth for resultList at theQuitDelay against scripttitle beside theSubTitle
				repeat
					try
						-- dialogen er spesiell 
						tell application (path to frontmost application as text)
							display dialog theSubTitle & ":
Enter the target length " & "and choose the dimension of the " & "image (w:" & item 1 of resultList & ", h: " & item 2 of resultList & ") to scale to the target size:" buttons {"Cancel", "Height", "Width"} default answer "640" with title scripttitle default button 2 cancel button 1 with icon caution giving up after (theQuitDelay - 1)
						end tell
						copy {button returned, text returned, gave up} of result to {target_dimension, target_length, userIgnored}
						if userIgnored then
							return null
						else
							set target_length to target_length as integer
							exit repeat
						end if
					on error e number n
						if n ≠ -128 then
							beep
						else
							return null
						end if
					end try
				end repeat
				return {target_dimension, target_length}
			end chooseSizeForHeightOrWidth
			
			
			
			on scaleChosenSide for the_item against scripttitle beside theSubTitle
				set resultList to getImageDimensions of img for the_item against scripttitle beside theSubTitle
				-- TODO, hadde vært best å velge image formats her!
				
				if the resultList is null then return null
				try
					tell application id "com.apple.imageevents"
						-- start the Image Events application
						launch
						set quit delay to my img's quitDelay
						-- open the image file
						set this_image to open the_item
						-- check if scaling is doable on this item
						copy file type of this_image to ImageFormat
						set ImageFormat to my img's presentFType(ImageFormat)
						if ImageFormat is not in my img's saveFormats then
							set canUseOriginalSaveFormat to false
						else
							set canUseOriginalSaveFormat to true
						end if
						
						
						if not canUseOriginalSaveFormat then
							set newFormat to chooseNewSaveFormat of (my img) for ImageFormat by my img's quitDelay against scripttitle beside theSubTitle
							if newFormat is null then
								try
									-- purge the open image data
									close this_image
									-- for the case that the user left the comp, so image events quit on us!
									-- set back the quit after idle delay
									set quit delay to 60
								end try
								return null -- The user declined the operation
							end if
						end if
						chooseSizeForHeightOrWidth of me for resultList at quitDelay against scripttitle beside theSubTitle
						if result is not null then
							copy result to {target_dimension, target_length}
						else
							try
								-- purge the open image data
								close this_image
								-- for the case that the user left the comp, so image events quit on us!
								-- set back the quit after idle delay
								set quit delay to 60
							end try
							return null -- The user declined the operation
						end if
						-- set back the quit after idle delay
						set quit delay to 60
						-- derive new name for the new image file
						copy my img's derive_filename((the_item as alias), "", "-", "") to {new_name, target_HFSpath}
						
						-- get dimensions of the image
						copy dimensions of this_image to {W, H}
						-- determine scale length
						if the target_dimension is "Height" then
							if W is less than H then
								set the scale_length to the target_length
							else
								set the scale_length to (W * target_length) / H
								set the scale_length to my img's rnd(scale_length)
							end if
						else -- target dimension is Width
							if W is less than H then
								set the scale_length to (H * target_length) / W
								set the scale_length to my img's rnd(scale_length)
							else
								set the scale_length to the target_length
							end if
						end if
						-- TODO: faktorisere ut denne biten også!
						if not canUseOriginalSaveFormat then
							copy my img's derive_filename((the_item as alias), newFormat, "-", "") to {new_name, target_HFSpath}
							save this_image as my img's getFType(newFormat) in file target_HFSpath
							-- purge the open image data
							close this_image
							set new_image to open target_HFSpath
							-- perform action
							scale new_image to size scale_length
							-- save the changes
							save new_image with icon
							-- purge the open image data
							close new_image
						else
							-- derive new name for the new image file
							copy my img's derive_filename((the_item as alias), "", "-", "") to {new_name, target_HFSpath}
							scale this_image to size scale_length
							-- save the changes
							-- save this_image with icon
							save this_image in file target_HFSpath with icon
							-- purge the open image data
							close this_image
						end if
					end tell
					notify of img about target_dimension & " scaled to " & target_length & " px." against scripttitle beside theSubTitle
					return target_HFSpath
				on error errMessage number errNr
					showErrMsg of img by errMessage at errNr against scripttitle beside theSubTitle
					return null
				end try
			end scaleChosenSide
			
			on scaleByFactor for the_item against scripttitle beside theSubTitle
				repeat
					try
						ddWthoutColor of img about (0.75 as string) by "Set the factor by which you want to scale the image with." against scripttitle beside theSubTitle
						copy the result to {text returned:scalingFactor, gave up:gaveUp}
						if gaveUp then return null
						set scalingFactor to scalingFactor as number
						exit repeat
					on error e number n
						if n ≠ -128 then
							beep
						else
							return null
						end if
					end try
				end repeat
				set target_HFSpath to performScalingByFactor for the_item against scalingFactor by scripttitle beside theSubTitle
				return target_HFSpath
			end scaleByFactor
			
			on scaleByPercentage for the_item against scripttitle beside theSubTitle
				repeat
					try
						ddWthoutColor of img about "50" by "Set the percentage by which you want to scale the image with." against scripttitle beside theSubTitle
						copy the result to {text returned:scale_percentage, gave up:gaveUp}
						if gaveUp then return null
						set scale_percentage to scale_percentage as number
						if the scale_percentage is greater than 0 then
							set the scalingFactor to the scale_percentage * 0.01
							exit repeat
						else
							error
						end if
					on error e number n
						if n ≠ -128 then
							beep
						else
							return null
						end if
					end try
				end repeat
				set target_HFSpath to performScalingByFactor for the_item against scalingFactor by scripttitle beside theSubTitle
				return target_HFSpath
			end scaleByPercentage
			
			on superSizedLargestSide for resultList
				set W to item 1 of resultList
				set H to item 2 of resultList
				if W is less than H then
					set the target_length to H
					set the scale_length to (H * target_length) / W
					set the scale_length to ¬
						img's rnd(scale_length)
				else
					set the target_length to W
					set the scale_length to (W * target_length) / H
					set the scale_length to ¬
						img's rnd(scale_length)
				end if
				return scale_length
			end superSizedLargestSide
			
			on downSizeLargestSide for resultList
				set W to item 1 of resultList
				set H to item 2 of resultList
				if W is less than H then
					set the scale_length to ¬
						img's rnd(W)
				else
					set the scale_length to ¬
						img's rnd(H)
				end if
				return scale_length
			end downSizeLargestSide
			
			to scaleImageUp for the_item against scripttitle beside theSubTitle
				set resultList to getImageDimensions of img for the_item against scripttitle beside theSubTitle
				if the resultList is null then return null
				set superSize to superSizedLargestSide for resultList
				set target_HFSpath to performScalingBySize for the_item by superSize at "Largest" against scripttitle beside theSubTitle
				return target_HFSpath
			end scaleImageUp
			
			to scaleImageDown for the_item against scripttitle beside theSubTitle
				set resultList to getImageDimensions of img for the_item against scripttitle beside theSubTitle
				if the resultList is null then return null
				set downSize to downSizeLargestSide for resultList
				set target_HFSpath to performScalingBySize for the_item by downSize at "Largest" against scripttitle beside theSubTitle
				return target_HFSpath
			end scaleImageDown
		end script
		
		set i to 1
		with timeout of img's quitDelay seconds
			repeat
				set choice to chooseCommand of img from commandList about i by img's quitDelay against scripttitle
				if choice is false then
					exit repeat
				else
					set subMenuText to text 4 thru -1 of (choice as text)
					if choice is showSomeHelp then
						set i to 1
						showProcessInfo of img for scalingInfo against scripttitle beside subMenuText
						set res to null
					else if choice is showCurInfo then
						set i to 2
						showImageInfo of img for this_item against scripttitle beside subMenuText
						set res to null -- so we don't bail out just yet
					else if choice is chooseDifferentImage then
						set i to 3
						set this_item to chooseImageFile of img by this_item against scripttitle beside subMenuText
						if this_item is null then
							exit repeat
						else
							set res to null -- so we don't bail out just yet
						end if
					else if choice is continueInPreview then
						continueInPreview of img for this_item against scripttitle beside subMenuText
						exit repeat
						
					else if choice is scaleLargestSide then
						set i to 5
						set res to scaleLargestSide of scaleImages for this_item against scripttitle beside subMenuText
					else if choice is scaleSmallestSide then
						set i to 6
						set res to scaleSmallestSide of scaleImages for this_item against scripttitle beside subMenuText
					else if choice is scaleChooseSide then
						set i to 7
						set res to scaleChosenSide of scaleImages for this_item against scripttitle beside subMenuText
					else if choice is scaleByPercentage then
						set i to 8
						set res to scaleByPercentage of scaleImages for this_item against scripttitle beside subMenuText
					else if choice is scaleByFactor then
						set i to 9
						set res to scaleByFactor of scaleImages for this_item against scripttitle beside subMenuText
					else if choice is scaleImageUp then
						set i to 10
						set res to scaleImageUp of scaleImages for this_item against scripttitle beside subMenuText
					else if choice is scaleImageDown then
						set i to 11
						set res to scaleImageDown of scaleImages for this_item against scripttitle beside subMenuText
					end if
					if res is not null then
						lookAtEndResult of img for res against scripttitle beside subMenuText
						exit repeat
					end if
				end if
			end repeat
		end timeout
	end if
end run

Wow, nicely done gents.

I will have a look and get on it when I have some free time. Thanks.