Store image dimensions on the comment field

I am trying to build a script that will transverse a directory and all its subfolders looking for images.

Every time an image is found, it reads its dimensions and stores them as a comment on the file spotlight comments field. What I have is this:

set folderToProcess to (choose folder with prompt "Choose Folder::")

tell application "Finder"
	set fileExt to {".png"}
	set theTopFolder to (folderToProcess as alias)
	repeat with EachFile in (get every file of theTopFolder)
			copy name of EachFile as string to FileName
			if name extension of EachFile is "png" then
				tell application "Image Events"
					set image_ to open EachFile
					set {width_, height_} to dimensions of image_
					close image_
				end tell
				set comment of EachFile to (width_ & " x " & height_ as text)
			end if
		end try
	end repeat
end tell

In theory, this code of mine is able to process all the files in a chosen folder, the problem is that the script hangs on the “tell application image events” part. I have to kill the applescript editor on the task manager.

In fact, this script of mine is just processing PNGs but I want it to process all images. How do I do that? How can I do something like “if finder item is kind images”…



the problem of your script is that Image Events doesn’t know Finder specifier objects.
This is a different approach, it uses Spotlight to filter the images
If the file has already any comment, the dimensions are appended

set folderToProcess to (choose folder with prompt "Choose Folder:")
set shellCmd to "mdfind image -onlyin " & quoted form of POSIX path of folderToProcess
set allImages to paragraphs of (do shell script shellCmd)
repeat with anImage in allImages
	set isValid to true
	tell application "Image Events"
			set currentImage to open anImage -- works also with POSIX paths
			set {imageWidth, imageHeight} to dimensions of currentImage
			close currentImage
		on error
			set isValid to false
				close currentImage
			end try
		end try
	end tell
	if isValid then
		set currentImagePath to POSIX file anImage as text
		set imageDimensions to ((imageWidth as text) & " x " & imageHeight)
		tell application "Finder" to set existingComment to comment of file currentImagePath
		if existingComment = "" then
			set newComment to imageDimensions
			set newComment to existingComment & return & imageDimensions
		end if
		tell application "Finder" to set comment of file currentImagePath to newComment
	end if
end repeat

Hi Stefan, thanks for the script, but strangely the script just worked for JPEG, TGA, TIFF and BMP images, but not for GIF, PNG or PSD.

try this alternative to the set shellCmd line

set shellCmd to "mdfind -onlyin " & quoted form of POSIX path of folderToProcess & space & quoted form of "kMDItemContentTypeTree  == '*public.image*'"

thanks Stefan…
it is perfect now!

You are an AppleScript GOD! :o