Quickly Getting Placeholder Images With Unsplash Source

I often find myself needing a batch of placeholder images when testing or creating dummy content within projects. Unsplash is a great source for these but downloading each image and making them a reasonable size can take time. They do offer an API but it’s highly limited without creating an account and, even then, getting random images will still take multiple requests.

Fortunately, they offer Unsplash Source. This allows easy direct links to images with the idea you can directly use unsplash source images in online projects. This also provides a very simple API to get random images. A request to https://source.unsplash.com/random/400x200?cat will redirect to a 400px wide by 200px high random picture of cat.

Building a Script

The below is a simple bash script uses unsplash source to get $COUNT many (Where $COUNT is the first argument passed when the script is called) images from unsplash. A second/third/fourth argument, for width/height/topic respectively, can be passed. A delay is added between image fetches to decrease the chances of duplicate images appearing.

#!/bin/bash

# Argument Variables
COUNT=$1
WIDTH=${2:-"1200"}
HEIGHT=${3:-"600"}
TOPIC=${4:-""}

# Show help when now arguments are passed
if [ -z "$COUNT" ]
then
    echo "--- unsplash-get ---"
    echo "Usage:   unsplash-get <count> [width=1200] [height=600] [topic]"
    echo "Example: unsplash-get 50"
    echo "Example: unsplash-get 5 250 250 cats"
    echo "--------------------"
    exit 0;
fi

# Adjust filename to include topic if provided
PREFIX="${TOPIC}_"
if [ -z "$TOPIC" ]
then
    PREFIX=""
fi

# Get our images
for i in $(seq 1 $COUNT)
do
    echo "Fetching image ${i} of ${COUNT}"
    curl -sL "https://source.unsplash.com/random/${WIDTH}x${HEIGHT}?${TOPIC}" > "${PREFIX}image_${WIDTH}x${HEIGHT}_$i.jpg"
    sleep 0.6
done