Random Images and Automator

Hi - I’ve just started to use Automator to get a certain image from a Finder folder to add as an attachment to an outgoing email.

Is there a way to have Automator select a RANDOM image from a Finder folder or, indeed, from a designated album in the photos app, to attach to an email?

Many thanks for considering this.

All good wishes,

Brian

You could use a short set of shell commands to choose a random file from a directory, and then take the result of that to do the subsequent processing. Automator does support shell script.

This gets a list of the content of my Documents folder, removes any directories from the list, sorts it randomly, and then takes the first entry from the top of the list.

ls -p ~/Documents | grep -v / | sort --random-sort | head -n 1

It might also be worth reviewing the use of Automator for this vs say Shortcuts. If Shortcuts is an option for you to use, then you may find it even easier to do things like select a file at random.

Thanks again for coming back on one of my questions.

I have done the following:

  1. I have created a folder in my Documents called ‘Images’.
  2. I have adapted your shell script as shown in the attached image.
  3. The script seems to be working but gives me a file name rather than the image I would really want to add.

Can you advise on what I am doing wrong here.

Thank you very much for doing this for me. :slight_smile:

All good wishes,

Brian



Okay, so your original post suggested that you were selecting an image via your Automator workflow that would then add it as an e-mail attachment. As you included no details of your workflow, I was providing a way to get the filename for the file - i.e. the way to identify the random image. So as you implemented it, it is doing exactly what I intended it to, but this does not match into your overall process whereby it seems you want to copy an image to the clipboard and then paste it into an e-mail.

Here’s a revised script that when executed should choose the random file from your Images folder, and then put the file onto the clipboard using a bit of AppleScript. At least it does for me when I have just tested it on my laptop.

#!/bin/zsh

theFolder=$HOME/Documents/Images
theFile=$(ls -p $theFolder | grep -v / | sort --random-sort | head -n 1)
theFilePath=$theFolder/$theFile
osascript -e 'set the clipboard to POSIX file "'$theFilePath'"'

That should bring it down to just one Automator Run Shell Script action.

See if that gets you what you are after.

Hi Stephen

First let me say I’m sorry if I misled you on my initial question. It wasn’t my intention. I’m not a coder and so my language may be imprecise.

Thank you very much for expanding the code for me.

I’m testing it later this week and will let you know how I get on.

Again, apologies for any misunderstanding.

All good wishes,

Brian