Python help - stretched images on Inky Impression 7

Hi all,

I’m using the inky Impression 7 display as a photo frame (and loving it). I’ve got a cron job every ten minutes to execute the below python script that selects a random (photo) file and displays it. Trouble I’m having is with portrait photos - it stretches them to the fit the screen. I’m wondering if there is a way I can leave portrait photos un-resized, centered, with a white background…?

Thanks in advance.

Matt

#!/usr/bin/env python3

import os
import random
from PIL import Image
#from inky import InkyPHAT
from inky.auto import auto

# Set up the Inky display
#inky_display = InkyPHAT("black")  # Use "black" for Inky Impression 7

#from pimoroni examples
inky = auto(ask_user=True, verbose=True)
saturation = 0.5

# Path to the directory containing images
image_directory = "/home/pi/photos"

# Get a list of all image files in the directory
image_files = [f for f in os.listdir(image_directory) if f.endswith(('.png', '.jpg', '.jpeg'))]

# Check if there are any images
if not image_files:
    print("No images found in the specified directory.")
else:
    # Randomly select an image
    selected_image = random.choice(image_files)
    image_path = os.path.join(image_directory, selected_image)

    # Load the image
    img = Image.open(image_path)

    # Resize the image to fit the display (if necessary)
    img = img.resize(inky.resolution)

    # Convert the image to the appropriate mode
    img = img.convert("RGB")

    # Display the image
    inky.set_image(img)
    inky.show()

    print(f"Displayed image: {selected_image}")