Search code examples
macosapplescriptautomator

Change width of image and adjust height automatically with Quick Action


If you have an image file, you can do the following:

  • Open the file in Apples Preview app
  • Go to: Tools>Adjust size…
  • Check "Scale proportionally"
  • Change the value in "Width:", in my case to 100 pixels

This looks like this:

Adjust size in Apples Preview app

This will change the width of the image and automatically adjust the height, without cutting the image.

I'd like to create a Quick Action, which does that for me: change the width to 100 px and adjust the height automatically.

Is it possible, to do that with Automators Quick Action editor?


Solution

  • sips is a Mac-specific, Apple-written command-line program with some basic image processing actions. The --resampleWidth option does what you need. (Can get more details on what sips can do via man sips within Terminal.)

    This sips command would resize an image to the size you want:

    sips --resampleWidth 100 path/to/image.png
    

    To use it within Automator, we can wrap that in this code:

    for f in "$@"
    do
        sips --resampleWidth 100 "$f"
    done
    

    This can then be triggered with the Run Shell Script Automator action:

    automator configuration

    Notes/caveats

    1. If the original image is smaller than 100px wide, this command will scale it to be larger than it originally was.

    2. Also, as pointed out in the comments, using sips may result in some metadata which is in the original image not being present in the scaled copy.

    Rotation problems?

    In the comments it's suggested that sips doesn't work correctly with images rotated 90°(/270°). I tested this and it appeared to work as expected, with the width of the output image being 100 in both cases.

    90 degree rotation test

    Images tested were rotated using Preview. It's my understanding that there are two types of image rotation:

    1. The image is re-saved with all the pixels in the new, rotated positions.
    2. The pixel data is unchanged, and data is added to the image to say 'read in all the pixel data, then before you display it, translate everything (e.g.) 90°'.

    The second approach avoids resaving, which may be problematic with lossy formats, as multiple rotations would lose data each time, i.e., four rotations would not end up with the original data again. I vaguely remember some problems using sips with this kind kind of image rotation, but it looks to me that it's potentially now been fixed. I'm using build 294 of sips [as displayed by typing sips -v into Terminal] with Mac OS Catalina (10.15.7).

    For certainty I'd suggest testing with a lossy format such as JPEG to see if Preview/sips behave differently with rotations.