Interactive program to resize images generated using ChatGPT

Created: by Pradeep Gowda Updated: Oct 06, 2023 Tagged: chatgpt · python

The inspiration for this exercise came from this post where I noted down the need for a “workflow” (I was thinking Alfred workflow) to process my photos for use in this website (see example), but turns out writing out the prompt for ChatGPT resulted in a much simpler solution.

Prompt

write a interactive command line program that asks the user for 1. input image file name ending in .heic 2. output file name (assume .png if no extension nothing is provided) 3. output resolution in the format 800, where 800 is the width

resize the image file with max width provided in input 3 above, while storing it in the appropriate file name and extension and store it in $HOME/files.btbytes.com/pictures/YYYY/MM where YYYY and MM correspond to today’s date.

ChatGPT output

Certainly. Here’s a Python script to achieve this using the PIL (Pillow) library:

import os
from datetime import datetime
from PIL import Image

def get_user_input():
    input_file = input("Enter input image filename ending in .heic: ")
    output_file = input("Enter output file name (or leave blank for .png): ")
    width = int(input("Enter output resolution width (e.g., 800): "))
    return input_file, output_file, width

def process_image(input_file, output_file, width):
    # Open and resize the image
    with Image.open(input_file) as img:
        aspect_ratio = img.height / img.width
        new_height = int(aspect_ratio * width)
        img = img.resize((width, new_height))

        # Determine output path
        today = datetime.today()
        year = today.strftime('%Y')
        month = today.strftime('%m')
        output_dir = os.path.expanduser(f'$HOME/files.btbytes.com/pictures/{year}/{month}')

        if not output_file.endswith(('.png', '.jpg', '.jpeg')):
            output_file += '.png'

        output_path = os.path.join(output_dir, output_file)

        # Create directory if doesn't exist
        os.makedirs(output_dir, exist_ok=True)

        # Save the image
        img.save(output_path)
        print(f"Image saved to {output_path}")

def main():
    input_file, output_file, width = get_user_input()
    process_image(input_file, output_file, width)

if __name__ == '__main__':
    main()

Before running the script, ensure you’ve installed the required packages:

pip install Pillow

Run the script, provide the inputs as prompted, and it will save the resized image in the specified directory structure.

Modifications

I saved the modified program as ~/btbytes/bin/proc_image.py.

import os
from datetime import datetime
from PIL import Image


def get_user_input():
    input_file = input("Enter input image filename ending in .heic: ")
    output_file = input("Enter output file name (or leave blank for .png): ")
    caption = input("Figure Caption")
    width = int(input("Enter output resolution width (e.g., 800): "))
    return input_file, output_file, caption, width


def process_image(input_file, output_file, caption, width):
    # Open and resize the image
    with Image.open(input_file) as img:
        aspect_ratio = img.height / img.width
        new_height = int(aspect_ratio * width)
        img = img.resize((width, new_height))

        # Determine output path
        today = datetime.today()
        year = today.strftime("%Y")
        month = today.strftime("%m")
        output_dir = os.path.expanduser(f"~/files.btbytes.com/pictures/{year}/{month}")

        if not output_file.endswith((".png", ".jpg", ".jpeg")):
            output_file += ".png"

        output_path = os.path.join(output_dir, output_file)

        # Create directory if doesn't exist
        os.makedirs(output_dir, exist_ok=True)

        # Save the image
        img.save(output_path)
        print(f"Image {output_file} saved to {output_path}")
        uri = output_path.replace(os.path.expanduser("~"), "")
        print(
            f"""
<figure>
  <img src="https://{uri}" alt="{caption}">
  <figcaption>{caption}</figcaption>
</figure>"""
        )


def main():
    input_file, output_file, caption, width = get_user_input()
    process_image(input_file, output_file, caption, width)


if __name__ == "__main__":
    main()

I Copy and paste the figure code spit out by the above script into my markdown file.

Summary

It is possible to generate a near complete program to write automation tasks using ChatGPT. The more time you take to write a complete and detailed spec, the more likely you are to get “scripts” to automate a few workflows.

In the above case, it even used a library (Pillow) that I know, but not overly familiar.

When I’m using ChatGPT, I (and you) spend more time thinking and writing what the program should do and later on verifying that it indeed fits your earlier specification.