If you ever needed to quickly stack two images on top of each other, this simple helper function gets the job done without any hassle. It figures out the correct dimensions, creates a fresh white canvas, and pastes both images vertically in the right position. It’s a clean, reusable helper that saves you time whenever you’re working with automated image generation or preparing visuals for your projects.
from PIL import Image
def join_images_vertically(img1:type[Image], img2:type[Image]):
"""Join two PIL images vertically."""
# Get dimensions
width1, height1 = img1.size
width2, height2 = img2.size
# Width as max of both and height as the sum
new_width = max(width1, width2)
new_height = height1 + height2
# Blank image with white background
new_img = Image.new("RGB", (new_width, new_height), color=(255, 255, 255))
# Paste both images
new_img.paste(img1, (0, 0))
new_img.paste(img2, (0, height1))
return new_img
