Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Using AppleScript / Automator to crop and save images

I am trying to help our graphics artists with a relatively easy task.


We have pictures of about 1000 employees. They are not uniform in size, composition, layout, etc. They are generally large files, 1 to 10MG.


From these we need to generate a square image of 500 x 500 px that has the employee's face centered, and is maybe 50K or so in size. We are putting these pictures on the web.


My understanding is that the graphics people are doing everything by hand. I think all of these steps could be automated except the actual crop.


First step would be to copy the file to a new folder and to reduce the size.


Then make a square crop without actually hitting the done button. Then the user could move to the exact crop. Then continue on with a second script or continuation of the first that would crop the picture, change image to 500x500 and then do a web export with quality set at 25% or something.


I know a little scripting and got a script started but got stalled on the cropping part.


Could anyone please assist me?


I only have the first part of the script


tell application "Acorn"

activate

tell document

crop square {500}

end tell

end tell

MacBook Pro (15-inch Mid 2012), OS X Mavericks (10.9.1)

Posted on Feb 8, 2016 8:40 AM

Reply
Question marked as Best reply

Posted on Feb 21, 2016 3:34 AM

First, backup all data.


Optimal results are achieved by cropping individual images manually. The main challenge is fixed positioning a rectangle to frame the subject in an aesthetically pleasing manner for each image given varied compositions among a set of images. If you want to introduce automation to the process, you can create a crop rectangle relative to the subject’s face. This requires face detection algorithms as is included in a computer vision and machine learning software library like OpenCV. One option is to install OpenCV with Homebrew and modify an existing Python script such as facedetect with Sublime Text for use with ImageMagick in a Bash script.


Create a small sample size folder of n number of jpeg images, selected by variation in size, composition, layout, etc.


If not already installed, install Xcode from the Mac App Store. You can agree to the Xcode license from the command-line in Terminal; enter your password when prompted:


sudo xcodebuild -license


From a Terminal shell, install Homebrew with the following command:


/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)”


Install ImageMagick with the following command:


brew install imagemagick


Install OpenCV with the following command:


brew tap homebrew/science && brew install opencv


Homebrew may require you to update PYTHONPATH, If so...copy and paste the following line into your .bash_profile and save:


export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages


Reload your .bash_profile with the following command:


source ~/.bash_profile


Download and install Sublime Text.


Download facedetect.


Open the facedetect-master folder you downloaded and move the facedetect executable to your Desktop. Duplicate (Control-click, select Duplicate) the facedetect executable. Move the original facedetect executable into your /usr/local/bin directory (Shift-Command-G from Finder). Option-click the copy you made, select Open With, and select Sublime Text. With the facedetect copy open in Sublime Text, change the path to haarcascade_frontalface_alt2.xml from:


# Profiles


PROFILES = {

'HAAR_FRONTALFACE_ALT2': '/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml'

}

User uploaded file

to:


# Profiles


# If in a diferent directory, change the path to the haarcascade xml

PROFILES = {

'HAAR_FRONTALFACE_ALT2':

('/usr/local/Cellar/opencv/2.4.12_2/share/'

'OpenCV/haarcascades/haarcascade_frontalface_alt2.xml')

}

User uploaded file

Replace the following lines near the end of the Python script:


else:


for rect in features:

print("{} {} {} {}".format(*rect))

User uploaded file

with the following lines:


# Decrease or increase any of the multiplier values for x y w h


else:

for rect in features:

x = int(rect[0] * 0.55) # smaller moves rect left; larger right

y = int(rect[1] * 0.45) # smaller moves rect up; larger down

w = int(rect[2] * 1.80) # rect width

h = int(rect[3] * 1.80) # rect height

print("{} {} {} {}".format(x, y, w, h))

User uploaded file

From Sublime Text save, not save as, the script. On your Desktop, rename (click the icon, then click the filename) the facedetect copy to something such as mfacedetect, “m” meaning modified. Move the mfacedetect executable to /usr/local/bin.


In Sublime Text, create a new file and paste the following lines into it:


#!/usr/bin/env bash


for file in /path/to/input_folder/*.jpg; do

name=$(basename "$file")

out=“/path/to/output_folder/$name"

cp "$file" "$out"

/usr/local/bin/facedetect "$file" | while read x y w h; do

mogrify -crop "${w}x${h}+${x}+${y}" \

-define jpeg:extent=55kb \

-strip \

-resize 500x500 +repage "$out"

done

done

User uploaded file

If you want to further optimize the file size of the crops, try the following ImageMagick settings in a separate Bash script:



#!/usr/bin/env bash


for file in /path/to/input_folder/*.jpg; do

name=$(basename "$file")

out=“/path/to/output_folder/$name"

cp "$file" "$out"

/usr/local/bin/mfacedetect "$file" | while read x y w h; do

mogrify -crop "${w}x${h}+${x}+${y}" \

-filter Triangle \

-define filter:support=2 \

-thumbnail 500 \

-unsharp 0.25x0.08+8.3+0.045 \

-dither None \

-posterize 136 \

-quality 82 \

-define jpeg:fancy-upsampling=off \

-interlace none \

-colorspace sRGB "$out"

done

done


Make sure to replace the placeholder paths above with the actual input and output folder paths. The path to the input folder is for the sample folder you created of jpegs. Save the Bash script to your Desktop with a name such as facedetect_crop.sh. Duplicate the script, open it in SublimeText, and replace "/usr/local/bin/facedetect” with "/usr/local/bin/mfacedetect” in the script. Save to your Desktop with a name such as mfacedetect_crop.sh. You can save them later to your Scripts folder if you choose. You now have two versions of the Bash script, one including a path to the facedetect executable and one including a path to the mfacedetect executable. Make sure to create separate output folders for each script. Make each script executable by using the following commands in a Terminal shell:


chmod u+x ~/Desktop/facedetect_crop.sh


and:


chmod u+x ~/Desktop/mfacedetect_crop.sh


Try out the facedetect_crop.sh by running it in Terminal:


~/Desktop/facedetect_crop.sh


This will create tight face crops derived from the face detection bounding rectangle in the facedetect Python script. The processed photos will be located in the output folder you specified. The crops will be 500x500 pixels in dimension and no larger than 55 kb in file size. Next, try out the mfacedetect_crop.sh by running it in Terminal:

~/Desktop/mfacedetect_crop.sh


This will create head and shoulders crops (or slightly tighter) derived from the face detection bounding rectangle in the mfacedetect Python script. The photos will be located in the output folder you specified. You can change the x and y values, which specify the co-ordinates for the top left corner of the crop rectangle (rect), and also change the width and height of the crop rectangle. If changing the width and height, input identical multiplier values to maintain a square crop rectangle. Save after each change. Run mfacedetect_crop.sh after each change to see the effect. If you prefer to make the Bash scripts on your Desktop clickable, change the extension from .sh to .command. When you double-click, a shell window will open and run the script, then close upon completion.


The crop rectangle is relative to the face detection bounding rectangle. The position of the face detection bounding rectangle for each image will in part vary depending on the rotation of the head.
User uploaded file
Consequently, no single set of x and y multiplier values can accommodate for head rotation in all images. It will be necessary to sort images based on whether the head is rotated, from the viewer’s point of view, to some extent toward the left or right image frame or is in a neutral center orientation. One suggestion is to run the images in the sample folder with one set of x and y values to judge the result based on criteria of how acceptable or pleasing the framing of the subject is. Classify the images that don’t meet the criteria and move them into separate folders based on whether the crop rectangle requires movement left or right, and run each folder through processing with the changed x and y values. Multiplier values you might start with:


Center orientation: 0.55 for x, 0.45 for y, 1.80 for both w and h

Left orientation: 0.30 for x, 0.45 for y, 1.80 for both w and h

Right orientation: 0.70 for x, 0.45 for y, 1.80 for both w and h

User uploaded file

Be aware that if selected multiplier values specify a crop rectangle beyond the image frame, the dimensions of the output image will be less than specified (500x500). When you are satisfied with the results on the sample images, you might want to create separate Python and Bash scripts for the left, right, and center processing of images. For instance: mfacedetect_right, mfacedetect_left, and mfacedetect_right for the Python executables, and mfacedetect_crop_right.sh, mfacedetect_crop_left.sh, and mfacedetect_crop_center.sh for the Bash scripts. For convenience, you can download them from this Dropbox link. Make sure to change the placeholder paths in the scripts.


Some things to keep in mind... The haarcascade_frontalface_alt2.xml, as its name implies, is for the detection of frontal faces. If there is too much tilt or rotation of the head in the image, the face likely won’t be detected. Some images with challenging illumination, occlusions (object partially blocking the face), or other confusion elements will make it difficult for the algorithm to detect faces. Consequently, it is unlikely the detection of faces will be 100%. Building on the work of Viola and Jones, ongoing research in face detection algorithms will continue to improve detection rates. By delving into OpenCV, other computer vision algorithms and libraries, including algorithms for thumbnail generation, and other image manipulation tools, you may discover more sophisticated scripts that eliminate the need for sorting images - scripts that employ facial feature detection for instance. Some examples of services that use face detection are Cloudinary, Thumbor, and Google Cloud Vision API; or fun applications such as Faceshift.


The above info should at least provide a starting point and serve as an example for what is possible.

10 replies
Question marked as Best reply

Feb 21, 2016 3:34 AM in response to Bryan Schmiedeler

First, backup all data.


Optimal results are achieved by cropping individual images manually. The main challenge is fixed positioning a rectangle to frame the subject in an aesthetically pleasing manner for each image given varied compositions among a set of images. If you want to introduce automation to the process, you can create a crop rectangle relative to the subject’s face. This requires face detection algorithms as is included in a computer vision and machine learning software library like OpenCV. One option is to install OpenCV with Homebrew and modify an existing Python script such as facedetect with Sublime Text for use with ImageMagick in a Bash script.


Create a small sample size folder of n number of jpeg images, selected by variation in size, composition, layout, etc.


If not already installed, install Xcode from the Mac App Store. You can agree to the Xcode license from the command-line in Terminal; enter your password when prompted:


sudo xcodebuild -license


From a Terminal shell, install Homebrew with the following command:


/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)”


Install ImageMagick with the following command:


brew install imagemagick


Install OpenCV with the following command:


brew tap homebrew/science && brew install opencv


Homebrew may require you to update PYTHONPATH, If so...copy and paste the following line into your .bash_profile and save:


export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages


Reload your .bash_profile with the following command:


source ~/.bash_profile


Download and install Sublime Text.


Download facedetect.


Open the facedetect-master folder you downloaded and move the facedetect executable to your Desktop. Duplicate (Control-click, select Duplicate) the facedetect executable. Move the original facedetect executable into your /usr/local/bin directory (Shift-Command-G from Finder). Option-click the copy you made, select Open With, and select Sublime Text. With the facedetect copy open in Sublime Text, change the path to haarcascade_frontalface_alt2.xml from:


# Profiles


PROFILES = {

'HAAR_FRONTALFACE_ALT2': '/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml'

}

User uploaded file

to:


# Profiles


# If in a diferent directory, change the path to the haarcascade xml

PROFILES = {

'HAAR_FRONTALFACE_ALT2':

('/usr/local/Cellar/opencv/2.4.12_2/share/'

'OpenCV/haarcascades/haarcascade_frontalface_alt2.xml')

}

User uploaded file

Replace the following lines near the end of the Python script:


else:


for rect in features:

print("{} {} {} {}".format(*rect))

User uploaded file

with the following lines:


# Decrease or increase any of the multiplier values for x y w h


else:

for rect in features:

x = int(rect[0] * 0.55) # smaller moves rect left; larger right

y = int(rect[1] * 0.45) # smaller moves rect up; larger down

w = int(rect[2] * 1.80) # rect width

h = int(rect[3] * 1.80) # rect height

print("{} {} {} {}".format(x, y, w, h))

User uploaded file

From Sublime Text save, not save as, the script. On your Desktop, rename (click the icon, then click the filename) the facedetect copy to something such as mfacedetect, “m” meaning modified. Move the mfacedetect executable to /usr/local/bin.


In Sublime Text, create a new file and paste the following lines into it:


#!/usr/bin/env bash


for file in /path/to/input_folder/*.jpg; do

name=$(basename "$file")

out=“/path/to/output_folder/$name"

cp "$file" "$out"

/usr/local/bin/facedetect "$file" | while read x y w h; do

mogrify -crop "${w}x${h}+${x}+${y}" \

-define jpeg:extent=55kb \

-strip \

-resize 500x500 +repage "$out"

done

done

User uploaded file

If you want to further optimize the file size of the crops, try the following ImageMagick settings in a separate Bash script:



#!/usr/bin/env bash


for file in /path/to/input_folder/*.jpg; do

name=$(basename "$file")

out=“/path/to/output_folder/$name"

cp "$file" "$out"

/usr/local/bin/mfacedetect "$file" | while read x y w h; do

mogrify -crop "${w}x${h}+${x}+${y}" \

-filter Triangle \

-define filter:support=2 \

-thumbnail 500 \

-unsharp 0.25x0.08+8.3+0.045 \

-dither None \

-posterize 136 \

-quality 82 \

-define jpeg:fancy-upsampling=off \

-interlace none \

-colorspace sRGB "$out"

done

done


Make sure to replace the placeholder paths above with the actual input and output folder paths. The path to the input folder is for the sample folder you created of jpegs. Save the Bash script to your Desktop with a name such as facedetect_crop.sh. Duplicate the script, open it in SublimeText, and replace "/usr/local/bin/facedetect” with "/usr/local/bin/mfacedetect” in the script. Save to your Desktop with a name such as mfacedetect_crop.sh. You can save them later to your Scripts folder if you choose. You now have two versions of the Bash script, one including a path to the facedetect executable and one including a path to the mfacedetect executable. Make sure to create separate output folders for each script. Make each script executable by using the following commands in a Terminal shell:


chmod u+x ~/Desktop/facedetect_crop.sh


and:


chmod u+x ~/Desktop/mfacedetect_crop.sh


Try out the facedetect_crop.sh by running it in Terminal:


~/Desktop/facedetect_crop.sh


This will create tight face crops derived from the face detection bounding rectangle in the facedetect Python script. The processed photos will be located in the output folder you specified. The crops will be 500x500 pixels in dimension and no larger than 55 kb in file size. Next, try out the mfacedetect_crop.sh by running it in Terminal:

~/Desktop/mfacedetect_crop.sh


This will create head and shoulders crops (or slightly tighter) derived from the face detection bounding rectangle in the mfacedetect Python script. The photos will be located in the output folder you specified. You can change the x and y values, which specify the co-ordinates for the top left corner of the crop rectangle (rect), and also change the width and height of the crop rectangle. If changing the width and height, input identical multiplier values to maintain a square crop rectangle. Save after each change. Run mfacedetect_crop.sh after each change to see the effect. If you prefer to make the Bash scripts on your Desktop clickable, change the extension from .sh to .command. When you double-click, a shell window will open and run the script, then close upon completion.


The crop rectangle is relative to the face detection bounding rectangle. The position of the face detection bounding rectangle for each image will in part vary depending on the rotation of the head.
User uploaded file
Consequently, no single set of x and y multiplier values can accommodate for head rotation in all images. It will be necessary to sort images based on whether the head is rotated, from the viewer’s point of view, to some extent toward the left or right image frame or is in a neutral center orientation. One suggestion is to run the images in the sample folder with one set of x and y values to judge the result based on criteria of how acceptable or pleasing the framing of the subject is. Classify the images that don’t meet the criteria and move them into separate folders based on whether the crop rectangle requires movement left or right, and run each folder through processing with the changed x and y values. Multiplier values you might start with:


Center orientation: 0.55 for x, 0.45 for y, 1.80 for both w and h

Left orientation: 0.30 for x, 0.45 for y, 1.80 for both w and h

Right orientation: 0.70 for x, 0.45 for y, 1.80 for both w and h

User uploaded file

Be aware that if selected multiplier values specify a crop rectangle beyond the image frame, the dimensions of the output image will be less than specified (500x500). When you are satisfied with the results on the sample images, you might want to create separate Python and Bash scripts for the left, right, and center processing of images. For instance: mfacedetect_right, mfacedetect_left, and mfacedetect_right for the Python executables, and mfacedetect_crop_right.sh, mfacedetect_crop_left.sh, and mfacedetect_crop_center.sh for the Bash scripts. For convenience, you can download them from this Dropbox link. Make sure to change the placeholder paths in the scripts.


Some things to keep in mind... The haarcascade_frontalface_alt2.xml, as its name implies, is for the detection of frontal faces. If there is too much tilt or rotation of the head in the image, the face likely won’t be detected. Some images with challenging illumination, occlusions (object partially blocking the face), or other confusion elements will make it difficult for the algorithm to detect faces. Consequently, it is unlikely the detection of faces will be 100%. Building on the work of Viola and Jones, ongoing research in face detection algorithms will continue to improve detection rates. By delving into OpenCV, other computer vision algorithms and libraries, including algorithms for thumbnail generation, and other image manipulation tools, you may discover more sophisticated scripts that eliminate the need for sorting images - scripts that employ facial feature detection for instance. Some examples of services that use face detection are Cloudinary, Thumbor, and Google Cloud Vision API; or fun applications such as Faceshift.


The above info should at least provide a starting point and serve as an example for what is possible.

Feb 21, 2016 11:34 PM in response to Roote

Typo in the post above: "For instance: mfacedetect_right, mfacedetect_left, and mfacedetect_right for the Python executables..." should be "For instance: mfacedetect_right, mfacedetect_left, and mfacedetect_center for the Python executables..."


In the above post, as tested with OS X Yosemite 10.10.5, Python 2.7.10, OpenCV 2.4.12, ImageMagick 6.9.3, Sublime Text 3, Build 3103, and Homebrew 0.9.5.


May be of interest, and even a cursory reading of, as well links in the post above, may go some ways to help answer why a "relatively easy task" for humans, whether the detection of faces or cropping images of people, is non-trivial for computers:


A Survey on Face Detection in the wild: past, present and future

DeepFace: Closing the Gap to Human-Level Performance in Face Verification

Feb 22, 2016 3:19 AM in response to Roote

Thanks for the incredibly detailed post.

Right now I am most interested in just getting the other two steps programmed .


>From these we need to generate a square image of 500 x 500 px that has the employee's face centered, and is maybe 50K or so in size. We are putting >these pictures on the web.

That is, I need a scrip to open the the file and change it to 500x500 - then the graphics person could do the cropping, and then a script to just save the file to a reasonable size.

I cannot even get that done.

Mar 5, 2016 6:41 PM in response to Bryan Schmiedeler

As always, backup all data.

Bryan Schmiedeler wrote:


That is, I need a scrip to open the the file and change it to 500x500 - then the graphics person could do the cropping, and then a script to just save the file to a reasonable size.


If you prefer not to auto-crop as described in the posts above...


Scale a source image to a different aspect ratio results in either horizontal squeezing or vertical squashing of the image. Simply batch crop a 500 x 500 pixel area at a single specified location from images in a set and there is no guarantee the face will even remain in all the crops given their varied compositions. Batch crop a 500 x 500 pixel area with the face centered, assuming the face of the subject for all the images in a set could be centered by some method other than face detection, too little of the image may remain to crop in a pleasing way. The image area remaining in the crop is of course dependent on the dimensions of the source image.


User uploaded file


Crop and resize an image with a minimum of 500 pixels in the smallest dimension, crop to frame the subject and resize to the specified 500 x 500 pixels, the image is degraded.


User uploaded file


If reducing the dimensions of an image prior to manual cropping is a requirement, with the assumption that the subject in an image is relatively centred and that their face is closer to the top of the image than the horizontal midline, you might try using a more generous crop without resizing as achieved using the following ImageMagick command. Keep in mind the image area remaining in the crop for each image will be variable due to the variable dimensions among the set of source images:


mogrify -crop 1000x1000+0+0 -gravity North +repage -strip -path /path/to/output_images/ /path/to/input_images/*.jpg


Ideally, in regards to image quality, crop and resize an image only as necessary. If resizing is required, do it once and only after cropping to minimize degrading the image. Assuming it could be scripted as you suggest, there is no image or efficiency benefit to batch resizing prior to manual cropping of individual images. There is an efficiency benefit to batch processing after manual cropping. Although you can batch resize in Preview, ImageMagick offers more control over parameters.

.

A suggested workflow using Preview and ImageMagick, as well as Finder and Terminal:


To prevent damage or loss, it is a best practice to never edit original images. Make two copies of the folder of original jpeg images on the Desktop. Rename one source_photos and the other working_photos. The source_photos folder is to copy individual images if necessary without the need to resort to the secured folder of original images. The working_photos folder is for opening and saving images while cropping. Create an empty third folder on the Desktop named processed_photos for saving to after resizing.


Open Preview. From the menu bar navigate to Preview > Preferences > General and make sure “Open all files in one window” is selected. Using Application Switcher, Command-Tab between Preview and Finder. Open and maximize a Finder window in column view. Click the working_photos folder. Decide how many images to open in Preview; one hundred for example. Hold down the Shift key and click the one hundredth image file. This will select all the images from the first to the hundredth. Assuming images open in Preview by default, press the Command-O keys to open them in a Preview window. If Preview isn’t the default app for opening images, Control-click and select Preview. Either way, maximize the Preview window once open. In Preview, select Thumbnails from the View menu if the images don’t appear in the sidebar. The filename of the first thumbnail image in the sidebar should be highlighted with the corresponding image in the content area displayed. If not highlighted, click on the first image in the sidebar. Press the Command-A to select all the images in the sidebar. Press the Command-9 keys to zoom all the images to fit to the size of the content area.


If a cross cursor doesn’t automatically appear in the content area when the cursor is hovering over the image, click the Markup Toolbar menu and select Rectangular Selection from the Selection Tools menu. Hold down the Shift key and drag the cursor to create a square Rectangular Selection frame of the proximate desired size for cropping. Position the cursor anywhere inside the frame. The cursor will change to an open hand icon. Click and drag the closed hand cursor to reposition the frame to the desired location. Resize the frame as necessary by positioning the cursor over a corner of the frame until a corner resize cursor appears; click and drag to resize.


User uploaded file


When satisfied with the framing of the subject in the image, release the Shift key and press the Command-K keys to crop. Press the Command-Z keys to reverse the crop if you wish to redo it.


User uploaded file


Press the Command-9 keys to zoom the cropped image to fit to the size of the content area.


User uploaded file


Press the Arrow-down key to move to the next image. Repeat the cropping process. If using a trackpad, optionally swipe upward with a two finger gesture to move down to the next image. When finished cropping the last image, click in the sidebar and press the Command-A keys to select all the images. Press the Command-S keys to save. Close the Preview window.


Press the Command-Tab keys to select Finder in the Application Switcher. In the Finder window you opened previously, click the hundredth-and-first image file in the working_photos folder. This will deselect the first hundred image files and highlight the image file you clicked on. Hold down the Shift key and click the two-hundredth image file. All one hundred of the second hundred images will be highlighted. Press the Command-O keys to open them in Preview. Repeat the cropping process as before.


Prior to beginning the cropping process, you may want to organize the image files in the working_photos folder into subfolders. For example, ten sequentially numbered subfolders named employee_photos containing one hundred images each for the approximately one thousand images. You may want to do this to simplify organization, to make it easier to track which images have been cropped over multiple sessions, or to distribute copies of a folder or folders to different individuals to process. You can do this using Terminal with the following commands.. First change to the working_photos directory:


cd ~/Desktop/working_photos


Confirm the working directory you are in:


pwd


When confirmed, create the subdirectories and move the images into them, one hundred images per subdirectory:


i=0; for f in *; do d=employee_photos_$(printf %03d $((i/100+1))); mkdir -p $d; mv "$f" $d; let i++; done


Confirm the subdirectories were created:


ls -1


Note that you can select all the images in a subfolder for cropping by clicking on one image file and pressing the Command-A keys to select all. As you finish cropping the images in each employee_photos subfolder, you may want to tag them as complete, with green for instance. You may also want to use a red tag for a subfolder if all the images within haven’t been cropped, as would happen if not completed over a single session, or if the processing of subfolders is non-sequential . You can select multiple images to tag.


User uploaded file


When all the images in all the subfolders have been cropped, you can move the images back into the working_photos parent folder and delete all the empty employee_photos subfolders. First though, backup the the working_folders folder by duplicating it on the Desktop. Then, in Terminal change to the working_photos directory:


cd ~/Desktop/working_photos


Confirm the working directory you are in:


pwd


When confirmed, copy all the files in the employee_photos subdirectories into the working_photos parent directory and remove the subdirectories using the -i switch for interactive mode:


find ./ -name '*.jpg' -exec mv '{}' ./ \; && rm -r -i ./*/


You’ll need to confirm removal of each subdirectory by typing “y” and pressing the Return key. If you prefer not to do this, you can substitute the following command without the need to confirm the removal of each subdirectory:


find ./ -name '*.jpg' -exec mv '{}' ./ \; && rm -r ./*/


Command-Tab to Finder to confirm the subfolders were deleted and all the images were moved to the working_photos folder. Whether or not you decide to create and employ subfolders in your workflow, once all the images have been cropped, the final step is to batch process all the images to the specified dimensions and file size. The following command uses ImageMagick in Terminal:


mogrify -define jpeg:extent=55kb \

-resize '500x500^’ \

+repage -strip \

-path ~/Desktop/processed_photos/ \

~/Desktop/working_photos/*.jpg


Confirm the processing of the images by opening the processed_photos folder in the column view of Finder. Keep in mind that differences in image quality between the final cropped and resized images depends in part on differences in the dimensions of the original images and the percentage of area cropped relative to each whole image.


Tested with OS X Yosemite 10.10.5, and ImageMagick 6.9.3.

Mar 7, 2016 12:05 AM in response to Bryan Schmiedeler

Hi Bryan. This script may be closer to what you envisioned. It assumes you are using Acorn as the image editor and that its Tool and Inspector Palettes are open with Crop selected. The script requires that Acorn is set as the default app to open the image file type, e.g JPEG, otherwise the images will open in a different app set as the default or you may get a Gatekeeper generated dialog similar to this one:

User uploaded file

You can change which application always opens a specific file type by clicking on a JPEG image file and pressing the Command-I keys. Change the "Open with" and "Change All" options:

User uploaded file User uploaded file

The script prompts you to select a folder and opens images one at a time for a user selectable time period which you can change in the script. When the time expires a dialog appears prompting you to extend the time, or if you are finished cropping the image, to load another image from the previously chosen folder.

User uploaded file

The script isn't robust in terms of error handling, the consequences of which boil down to avoiding clicking the "Load Next Image" button if not finished cropping an image, and avoiding loading images from the same folder across multiple sessions. Given this, you may want to create subfolders of the images, fifty or a hundred per subfolder. You can do this as outlined in an earlier post above or by using another method.


Once an image is loaded in Acorn, hold down the Shift key to create a square crop box by dragging the cursor across the image. Reposition the crop box by clicking and dragging the cursor inside the crop box. Press the Option-Command-K keys to crop, or by clicking the "Crop Image" button in Acorn's Inspector Pallete. Once cropping of an image is complete, click the "Load Next Image" button when the dialog appears after the user specified time expires. The next image will load for cropping.


The script includes a timeout override of AppleScript's default value of two minutes to allow for taking a break of up to an hour to avoid an error message and cessation of the running script. The timeout value can be changed in the script.


I intentionally didn't include resizing of the image prior to cropping over concerns of image degradation as outlined in an earlier post above. The script will resize an image after cropping to the specified 500 x 500 pixels and Web Export in the JPEG image format at 50% quality. As there seems to be no way to specify the output file size when scripting Acorn, you may need to adjust the quality setting for the amount of compression in the script to limit the file size to below the specified approx. 50 kB. As an example, a 342 kB crop of a 4.4 MB image using 50% quality reduced to 44 kB.


You can download the script from this Dropbox link: Acorn_crop_resize_web_export.scpt


Tested with OS X Yosemite 10.10.5, Acorn 5.3, Script Editor 2.7, and AppleScript 2.4. Check out Acorn's AppleScript dictionary from within Script Editor by navigating to File > Open Dictionary from the menu bar, selecting Acorn, and clicking the "Choose" button. Also refer to Acorn's documentation and scripting examples. Also refer to Apple's AppleScript Language Guide. Other resources include MacScripter, Mac OS X Automation, and Stack Overflow among others.

User uploaded file

-- Important! - Web Export overwrites the source file

-- Script requires Acorn is the default app to open the file type (e.g. JPEG)

tell application "Finder"

set aFolder to choose folder

set theFolder to files of aFolder

end tell

repeat with aFile in theFolder

open aFile

tell application "Acorn"

activate

delay 10 -- in seconds; time for cropping image, increase or decrease as desired

repeat

with timeout of 3600 seconds -- allows dialog to idle beyond default before errmsg and cessation of script

set dialogResult to display dialog ¬

"Enter a number in seconds and click \"More Time\", else if the image is cropped click \"Load Next Image\"" with title ¬

"I NEED MORE TIME!" default answer "" buttons ¬

{"More Time", "Load Next Image"} default button "More Time"

if text returned of dialogResult is not "" then

set delayTime to text returned of dialogResult

delay delayTime

else

if button returned of dialogResult is "Load Next Image" then exit repeat

end if

end timeout

end repeat

set saveFile to file of document 1

tell document 1

resize image width 500

web export in saveFile as JPEG quality 50 -- change quality as desired; change affects file size

close without saving

end tell

end tell

end repeat

Using AppleScript / Automator to crop and save images

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.