Skip to content

Instantly share code, notes, and snippets.

@muhammadanas0716
Created September 18, 2023 16:36
Show Gist options
  • Save muhammadanas0716/902df1fa64ee8476bba4396c06e81d4e to your computer and use it in GitHub Desktop.
Save muhammadanas0716/902df1fa64ee8476bba4396c06e81d4e to your computer and use it in GitHub Desktop.
import sys
import os
from PIL import Image, ImageOps
def overlay_shirt_on_image(input_path, output_path):
"""Overlay a transparent-background shirt image onto an input image."""
# Validate the extensions
input_ext = get_file_extension(input_path)
output_ext = get_file_extension(output_path)
if input_ext not in ['jpg', 'jpeg', 'png'] or output_ext not in ['jpg', 'jpeg', 'png']:
sys.exit("Invalid output")
if input_ext != output_ext:
sys.exit("Input and output have different extensions")
try:
# Open the images
input_img = Image.open(input_path)
except FileNotFoundError:
sys.exit("Input does not exist")
shirt_img = Image.open("shirt.png")
# Adjust the input image to fit the shirt size
fitted_img = ImageOps.fit(input_img, shirt_img.size)
# Overlay the shirt on the input
fitted_img.paste(shirt_img, (0, 0), shirt_img)
# Save the final image
fitted_img.save(output_path)
def get_file_extension(filename):
"""Extract and return the file extension from a filename."""
return filename.rsplit('.', 1)[-1].lower()
if __name__ == "__main__":
# Check for correct number of command-line arguments
arg_count = len(sys.argv)
if arg_count < 3:
sys.exit("Too few command-line arguments")
elif arg_count > 3:
sys.exit("Too many command-line arguments")
# Overlay the shirt
overlay_shirt_on_image(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment