Inspirational Quotes Image Generator in Python

2 min read • June 12, 2023

If you browse Pinterest, Instagram, or type “inspirational quotes Pinterest” in your browser, you’ll get tons of results, like these:

I decided to automate the process of creating these images with Python using the Pillow library.

It’s also my Harvard’s CS50P course final project (check out my CS50P review).

How does it work? 🤔

Short video demo:

and a graphic diagram of the process cause why not:

  1. I used the Pexels API to fetch images for the background. We can use the download_background() and get_backgrounds() functions to download one random picture with a matching query. I decided to go with “nature”.
    def get_backgrounds(page: int = 1):
    params = {
    "query": "nature",
    "orientation": "portrait",
    "page": page,
    "per_page": "40",
    return requests.get(
    "", params=params, headers=HEADERS
    def download_background(page: int = 1):
    # Get list of images
    images = get_backgrounds(page).get("photos")
    if not images:
    raise Exception("API Error")
    # Choose random one
    img_id = random.choice(images)["id"]
    download_url = f"{img_id}/download"
    print(f"Downloading image: {download_url.removesuffix('/download')}")
    # Download it
    response = requests.get(
    with open(BACKGROUND, "wb") as f:
  2. After getting the background image, we need to edit it. We will resize the background and darken it using edit_background() to prevent the image and text from blending together.
    def edit_background():
    # Resize background
    img =
    img = img.resize((W, H))
    # Change brightness
    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(0.55)
  3. Now it’s time to get the quote and its author. They’re stored in a CSV file (assets/quotes.csv). We just have to get a random one with the get_quote() function.
    def get_quote():
    # Get number of quotes and choose random one
    with open(QUOTES_FILE) as f:
    reader = csv.DictReader(f)
    rand_quote_num = random.randint(0, len(list(reader)) - 1)
    # Choose random quote
    with open(QUOTES_FILE) as f:
    reader = csv.DictReader(f)
    for i, row in enumerate(reader):
    if rand_quote_num == i:
    return row["Quote"], row["Author"] if row["Author"] else "Unknown"
  4. The last step is to insert the quote using the Pillow library. The toughest part is fitting the text onto the image. Quotes have different lengths, so we have to change the font size based on its length. I achieved it with the help of helper functions inside the ImageText class ( file).

The entire source code is available here if you want to check it out. 😀