Script for Image Events is overwriting my files with previously reformatted files of the same name
I have a simple Applescript to resize photos with Image Events. The photos are all of football players so they are all named by their number as in "1.jpg", "4.jpg" and so on. The issue I run into is when I do multiple batches of players in different directories the script will overwrite a photo with one from another team that has the same filename and was previously done. Again, these photos were all placed in different directories. The end result is after running successfully two or three times the reformatted photos of the players will get confused.
Here's what I have in the script to call Image Events.
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 290
-- 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_w开发者_StackOverflowidth) / 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) & "" & (name of this_item)
save this_image in new_item as typ
end tell
end rescale_and_save
You seem to have triggered a bug in Image Events processing multiple items with the same name. I'm not seeing the exact behavior you describe, but I am seeing similar behavior.
I'd suggest you simply tell Image Events to quit after processing each folder; that way it won't get confused. (You don't need the launch
, either; the only reason to use launch
is if you want a non-background application to open without presenting an untitled document window.)
Incidentally, if you want to overwrite the existing image with the scaled version, all you need is save this_image
. Image Events behaves much like any other application if you were to open a document, modify it, and save it.
精彩评论