use automator to crop images

I have several images called this way "100x200_120x220". The first sequence, 100x200, represents the visible size, and 120x220 represents the total size of the image. I would like to use Automator to cut the images to the visible size. Have to look into the file name for the size at which the image must be cropped. I have not seen any possibility in this regard. It's impossible?

Thank you.

Posted on Feb 28, 2019 7:51 AM

Reply
Question marked as Top-ranking reply

Posted on Mar 2, 2019 5:23 AM

Ok. I have put this Automator application on a diet and it now is a single action containing a Bash script. I have tested it by dropping single and multple files on a Finder toolbar icon of this application, and it saves the same named files into visible Finder directory with the extension set to jpg. The sips conversion tool does not automatically assign a new image format extension to the converted content. The Bash script also works standalone in the Terminal with .tiff filenames (or wildcards *.tiff) supplied on the command-line.


Tested on macOS High Sierra 10.13.6 (17G5019), and Mojave 10.14.3 (18D109). All test .tiff images were 300 dpi.


Workflow: (drag the tiff image(s) onto the toolbar icon, get cropped jpg results. The Automator app was dragged/dropped on the Finder window toolbar while holding the ⌘ key.



  1. Launch Automator from Dock: Launchpad : Other : Automator.
  2. New Document : Application
  3. Drag/drop the Run Shell Script action onto the larger workflow window
    1. Mojave: Automator library
    2. Pre-Mojave: Utilties Library
  4. Run Shell Script action
    1. Remove all default content
    2. Change pass in: as arguments
    3. Copy/paste Bash source code from below into Run Shell Script action
  5. Save to Desktop, and quit Automator
  6. Press ⌘ and drag Automator application to open Finder toolbar next to the search window.


#!/bin/bash

# Tiff image files dropped on this Automator application will be cropped
# based on the first two integers of the filename, at the fixed DPI, and
# written as same filename with jpg extension to original location.
# Works nicely in the Finder toolbar for drag/drop from current folder, or
# as standalone shell script taking files from the command-line.

# Additional info: man sips

# For filename 120x120_125x125.tiff, crop the 125 pixel square image
# to 120 pixels, and write out conversion to 120x120_125x125.jpg.

# Tested: macOS High Sierra 10.13.6 (17G5019)
#         macOS Mojave 10.14.3 (18D109)

# Version: 1.0
# VikingOSX, 2019-03-02, Apple Support Communities, No warranties of any kind.

# initialize these integer variables to zero
declare -i height=0 width=0

#  truncate sips log file
> ~/Desktop/hw.txt

# sips requires dpi in floating point
DPI="72.0"

# match on any tiff extension just in case
pattern="+(*.tif|*.tiff|.TIF|.TIFF)"

shopt -s extglob

for f in "$@"
do
    # skip files without tiff extensions
    [[ $f == $pattern ]] || continue

    # get just the extension from the filename
    ext="${f##*.}"
    # sips does not automatically assign new image format file extension
    outfile="${f%$ext}jpg"

    # assign the first two captured/reversed crop values of the filename
    read -r height width <<<$(sed -En 's/([0-9]+)x([0-9]+)_.*/\2 \1/p' <<<"${f##*/}")

    # crop but not scale at designated DPI with output to jpeg at 100% image quality.
    # This example appends sips stdout/stderr output to log file
    /usr/bin/sips --cropToHeightWidth $height $width -s dpiHeight $DPI -s dpiWidth $DPI \
     -s format jpeg -s formatOptions 100 "$f" --out "$outfile" >> ~/Desktop/hw.txt 2>&1
done

shopt -u extglob
exit 0



30 replies
Question marked as Top-ranking reply

Mar 2, 2019 5:23 AM in response to dragos2968

Ok. I have put this Automator application on a diet and it now is a single action containing a Bash script. I have tested it by dropping single and multple files on a Finder toolbar icon of this application, and it saves the same named files into visible Finder directory with the extension set to jpg. The sips conversion tool does not automatically assign a new image format extension to the converted content. The Bash script also works standalone in the Terminal with .tiff filenames (or wildcards *.tiff) supplied on the command-line.


Tested on macOS High Sierra 10.13.6 (17G5019), and Mojave 10.14.3 (18D109). All test .tiff images were 300 dpi.


Workflow: (drag the tiff image(s) onto the toolbar icon, get cropped jpg results. The Automator app was dragged/dropped on the Finder window toolbar while holding the ⌘ key.



  1. Launch Automator from Dock: Launchpad : Other : Automator.
  2. New Document : Application
  3. Drag/drop the Run Shell Script action onto the larger workflow window
    1. Mojave: Automator library
    2. Pre-Mojave: Utilties Library
  4. Run Shell Script action
    1. Remove all default content
    2. Change pass in: as arguments
    3. Copy/paste Bash source code from below into Run Shell Script action
  5. Save to Desktop, and quit Automator
  6. Press ⌘ and drag Automator application to open Finder toolbar next to the search window.


#!/bin/bash

# Tiff image files dropped on this Automator application will be cropped
# based on the first two integers of the filename, at the fixed DPI, and
# written as same filename with jpg extension to original location.
# Works nicely in the Finder toolbar for drag/drop from current folder, or
# as standalone shell script taking files from the command-line.

# Additional info: man sips

# For filename 120x120_125x125.tiff, crop the 125 pixel square image
# to 120 pixels, and write out conversion to 120x120_125x125.jpg.

# Tested: macOS High Sierra 10.13.6 (17G5019)
#         macOS Mojave 10.14.3 (18D109)

# Version: 1.0
# VikingOSX, 2019-03-02, Apple Support Communities, No warranties of any kind.

# initialize these integer variables to zero
declare -i height=0 width=0

#  truncate sips log file
> ~/Desktop/hw.txt

# sips requires dpi in floating point
DPI="72.0"

# match on any tiff extension just in case
pattern="+(*.tif|*.tiff|.TIF|.TIFF)"

shopt -s extglob

for f in "$@"
do
    # skip files without tiff extensions
    [[ $f == $pattern ]] || continue

    # get just the extension from the filename
    ext="${f##*.}"
    # sips does not automatically assign new image format file extension
    outfile="${f%$ext}jpg"

    # assign the first two captured/reversed crop values of the filename
    read -r height width <<<$(sed -En 's/([0-9]+)x([0-9]+)_.*/\2 \1/p' <<<"${f##*/}")

    # crop but not scale at designated DPI with output to jpeg at 100% image quality.
    # This example appends sips stdout/stderr output to log file
    /usr/bin/sips --cropToHeightWidth $height $width -s dpiHeight $DPI -s dpiWidth $DPI \
     -s format jpeg -s formatOptions 100 "$f" --out "$outfile" >> ~/Desktop/hw.txt 2>&1
done

shopt -u extglob
exit 0



Mar 13, 2019 9:21 AM in response to dragos2968

Ok. I have made some minor changes and it is cropping correctly in Automator now. Cropped your example image correctly too.


Replace the Bash code in your Run Shell Script with the following:


#!/bin/bash

# Overwrite images with cropped results based on the first n x n values
# of the filename. Since sips deals in pixels, we have to do the math
# from millimeters to pixels for the correct crop values.

# For image 120x120_125x125.jpg, crop the 125 pixel square image
# to 120 pixels.

# Reference: https://discussions.apple.com/thread/250198638
# Additional info: man sips

# Tested: macOS High Sierra 10.13.6 (17G5019)
#         macOS Mojave 10.14.3 (18D109)

# Version: 2.5, cleaned up match calculations for crop size.
# VikingOSX, 2019-03-13, Apple Support Communities, No warranties of any kind.

# initialize these integer variables to zero
declare -i height=0 width=0 cropHeight=0 cropWidth=0
# match on any regular JPG extension just in case
pattern="+(*.jpg|*.jpeg|*.jp2|*.JPG|*.JPEG|*.JP2)"

shopt -s extglob

for f in "$@"
do
    # skip files without pattern extensions
    [[ $f == $pattern ]] || continue

    # assign the first two captured/reversed crop values of the filename
    read -r height width <<<$(sed -En 's/([0-9]+)x([0-9]+)_.*/\2 \1/p' <<<"${f##*/}")
    # get the original image DPI. Skip first line of output in awk.
    read -r imgDPI_H imgDPI_W <<<$(sips -g dpiHeight -g dpiWidth "$f" | \
                                   awk 'NR>1 {print $2}')
    # convert mm to pixels for new crop pixel values rounded to nearest integer
    cropHeight=$(bc -l <<<"($imgDPI_H / 25.4) * $height" | cut -d. -f1)
    cropWidth=$(bc -l <<<"($imgDPI_W / 25.4) * $width" | cut -d. -f1)
    # crop image in-place while retaining its DPI
    /usr/bin/sips --cropToHeightWidth $cropHeight $cropWidth \
                  -s dpiHeight $imgDPI_H -s dpiWidth $imgDPI_W "$f"
done

shopt -u extglob
exit 0


Mar 1, 2019 5:11 PM in response to dragos2968

Ok. I have an Automator application that prompts you for the folder containing your .tif/.tiff images. It will also prompt you with a dialog where you click either a 72 dpi or 150 dpi button. Following that, sips will process each image file to a cropped (not scaled) RGB JPG file at the DPI setting, and with the JPG image quality set to 100. The cropped setting are taken from the first two integers in the file name, assuming cwxch_iwxih.tif/tiff. The c stands for cropped and the i for the original image dimensions. The original images are 300 DPI in my testing, and Preview verifies that the output JPG are exactly the crop dimensions, and the specified output DPI.


Tested on High Sierra 10.13.6 (17G5019), and still need to test on Mojave 10.14.3 (18D109). Then I will post it here. Probably tomorrow (3/2) at this point on a Friday evening.

Mar 5, 2019 5:04 AM in response to dragos2968

I exported my original artwork with CMYK 300 dpi as a 120x120_125x125 JPG file at 100 quality. When I use sips to crop this file at the calculated 1417 pixels, and at the original DPI, the output image is correctly cropped at 1417 pixels, and it retains the desired 120 mm. If I change the original DPI down to 72.0 DPI, then the crop remains pixel accurate, but the image is now 500 mm.


If I start with the same image, but as a TIFF, and use the image DPI, then the crop is accurate, but the resulting JPG is now 500 mm.


So, accuracy suggests that you use JPG (or PNG) not TIFF as drop files on this Automator solution, and leave them at the original image DPI. Of course, this begs the question — overwrite the original JPG in place with the cropped result, or append a 'c' to the output file to visually tell you that it has been cropped (e.g 120x120_125x125c.jpg)?


Once I have the answer to that question, I can post the updated script for use in the Run Shell Script action.


Mar 12, 2019 4:22 AM in response to dragos2968

Version 2.0 was my last post. It now restricts input images to JPG, gets the original image DPI, and using the first two (crop) values, calculates the millimeter to pixels conversion that sips requires. It then crops the existing JPG in-place.


Unlike TIFF, the JPG images do not expand their original millimeter size when cropped.


Did you try v2.0 above?

Mar 1, 2019 6:28 AM in response to VikingOSX

Hi VikingOSX, thanks for your reply.

From the beginning I want to tell you that I am 0 at coding. I used the Automator just for small stuff. Most often I use photoshop actions in my work. And what I need now can't be done with PS actions.


Yeah, I want to crop them, not to scale. But I want to do this regardless of the size they have. The images are tif, and at the end, after cropping I wanted to convert them to JPG rgb at 72 or 150 dpi, without changing their name or destination. Filenames could have the form: 12x12_13x13, 123x123_125x125 or 1234x1234_1235x1235 (ie with 2, 3 or 4 digits).


Can you show me 2-3 screenshots so I can replicate this workflow?


Thanks


Mar 1, 2019 11:03 PM in response to VikingOSX

Thank you, you're very kind.


No no, I was saying I didn't want to change the "file name". Normally, once converted, the extension will change. Do not bother to do it with dialogue. Leave it at 72. I suspect that if ever I need, I can edit it directly in Automator and modify the resolution or file type. I will make more droplets. I put them in the Finder toolbar and drag the files on it, as I do with the other ones. I don't want to prompts for the folder containing tif's. Just a simple drag and drop. All that matters is to crop to visible size and save it in the same location.

Mar 4, 2019 6:03 AM in response to dragos2968

The sips utility was written to assume pixels, not metric measurement. The Preview application shows image size in pixels, not millimeters, so your 120x120_125x125.tiff as millimeters (or 1417x1417_1476x1476 pixels) is listed as 1476 x 1476 pixels in Preview.


What I am seeing is that sips will automatically pass CMYK as the color space, and U.S. Web Coated (SWOP) v2 profile from the tiff image into the cropped jpg result when I test with a 300 dpi CMYK image created and exported from Affinity Photo.


There are some mm to pixel conversion calculations that need to be provided to sips — in order to perform accurate crops. Sips can extract the inbound image DPI value which is essential in the accurate per-image conversion of mm to pixels.


So that is what I am doing is now testing what it will take to tweak this solution to handle your millimeter image measurements.

Mar 4, 2019 8:49 AM in response to VikingOSX

I have a modification running here that converts a 300 dpi, CMYK 120x120_125x125.tiff (millimeters) or 1417x1417_1476x1476.tiff (pixels) into a 1417x1417 pixel jpg at 72 dpi. However, it is no longer 120mm x 120mm, it is now 500mm x 500mm, while Preview reports it as a CMYK 1417 x 1417 at 72 dpi jpg. Going from 300 dpi to 72 dpi introduces many more spaces between the pixels, and I do not believe there is a way to stay 120mm with reduced resolution — even by resampling both height and width.


Despite the first paragraph, it is cropping correctly.

Mar 4, 2019 11:12 AM in response to dragos2968

Placing a 120mm crop on a 125mm image works fine to produce a JPG with the original image DPI, color space, and profile at 1417 pixels. However, the millimeter measurement on the resulting JPG is 500mm square on a millimeter ruler. I am unable to achieve 1417 pixels and 120mm in the final image measurements using sips. This may also be a consequence of going from TIFF to JPG. If I invoke sips on the JPG resampling using the cropHeight and cropWidth using 72.0 dpi, then the only change with the JPG is it is 72 dpi, keeping the 1417 pixel and 500mm dimensions.


If I give you the JPG from the first paragraph, will you still need a Photoshop action?


I have revised the script to detect the original image DPI and use that to convert millimeters to pixels for both the cropHeight and cropWidth values:


(imageDPI / 25.4) * crop dimension in mm

Mar 12, 2019 6:45 AM in response to dragos2968

Without changing the v2.0 script, I created a 355mmx235mm (wxh) rectangle. Colored it blue. I then layered another rectangle above it sized at 300mmx200mm (wxh) and colored it green. Centered both layers and grouped. Exported as 72 dpi RGB JPG.


When I run the script, I am left with only the green rectangle which measures exactly 300mmx200mm. How is this not cropping accurately? If the script were not getting the millimeter to pixel conversion math done correctly, the preceding crop would have not been 300x200. Same results with a 300 dpi image of the preceding measurements.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

use automator to crop images

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