Photoshop "Optimize to file size" script

Hi everyone,

I am currently writing a script to circumvent Photoshop’s lack of scripting support for the “Optimize to File Size” option in the Save for Web command, but I’m having trouble with targeting the file sizes correctly.

Here is the code I’m using (forgive me, I know its not so graceful… I’m still very new). Basically it exports the image at 100% quality, checks the resulting file size against the desired file size, and if it’s not equal to or less than that value, it deletes, reduces the quality level, and re-exports until it meets that criteria:

on optimizeFile(currentDoc, optimizeSize, exportPath, fileExtension, trimmedFilename, qualityIncrement)
	set qualityLevel to 100
	set optimizedFile to ((exportPath & trimmedFilename & fileExtension) as string)
	
	tell application "Adobe Photoshop CS3"
		tell currentDoc
			export in file optimizedFile as save for web with options {class:save for web export options, quality:qualityLevel, web format:JPEG}
		end tell
	end tell
	tell application "Finder"
		set truncatedFile to files of alias exportPath whose name contains "#0"
		repeat with thisFile in truncatedFile
			set name of thisFile to (trimmedFilename & fileExtension)
		end repeat
		set fileSize to physical size of optimizedFile
	end tell
	repeat until fileSize is less than or equal to optimizeSize
		tell application "Finder"
			delete file optimizedFile
			set qualityLevel to (qualityLevel - qualityIncrement)
		end tell
		tell application "Adobe Photoshop CS3"
			tell currentDoc
				export in file optimizedFile as save for web with options {class:save for web export options, quality:qualityLevel, web format:JPEG}
			end tell
		end tell
		tell application "Finder"
			set truncatedFile to files of alias exportPath whose name contains "#0"
			repeat with thisFile in truncatedFile
				set name of thisFile to (trimmedFilename & fileExtension)
			end repeat
			set fileSize to physical size of optimizedFile		end tell
	end repeat
end optimizeFile

The problem that I am having is that when this script exports bigger images at bigger file sizes (even in the 30 to 40k range) it works perfectly. However, whenever I get to thumbnail sized images that i need to export at say 3k or 4k, it runs into an infinite cycle of deleting and re-exporting. I have tried using the “data size” property instead of “physical size” but that seems to ignore the loops altogether and export files at much larger sizes.

Can anyone out there help? I’d love to nail down a script that can do this function well, as I think there is a huge need for this functionality amongst people who regularly batch process images, i’m just afraid that my version may not be the most efficient.