Skip to content

Instantly share code, notes, and snippets.

@meta-hub
Last active October 20, 2021 07:49
Show Gist options
  • Select an option

  • Save meta-hub/b505f6e74cfdf9e356ed001464cc0cf0 to your computer and use it in GitHub Desktop.

Select an option

Save meta-hub/b505f6e74cfdf9e356ed001464cc0cf0 to your computer and use it in GitHub Desktop.
Merge files with Python
# merger.py
# A simple image merger utility script.
# Written by Brayden Haynes - itsBraydenHaynes@gmail.com
# usage:
# py merger.py mergefolder1 mergefolder2 mergefolder3 ...
import sys
import os, os.path
from PIL import Image
# Remove arg[0] ("merger.py") from sys.argv
sys.argv.pop(0)
# If no other arguments passed, exit
if len(sys.argv) <= 1:
print("not enough arguments passed, exiting now")
exit();
# If merged folder does not exist, create it now
if not os.path.exists("./merged"):
os.makedirs("./merged")
base_images = []
stack_images = []
base_path = "./" + sys.argv[0]
base_dir = os.listdir(base_path)
# Define "base images" to build from
for file_name in base_dir:
file_path = base_path + "/" + file_name
image = Image.open(file_path).convert("RGBA")
base_images.append(image)
# Remove base images from sys.argv
sys.argv.pop(0)
# Get all images that we want to stack ontop of each base image
for i in range(0, len(sys.argv)):
arg = sys.argv[i]
arg_path = "./" + arg
arg_dir = os.listdir(arg_path)
images = []
for file_name in arg_dir:
file_path = arg_path + "/" + file_name
image = Image.open(file_path).convert("RGBA")
images.append(image)
stack_images.append(images)
# Global stack count var, for merged filename
stack_count = 0
# Iterate stack images for merging
def iter_stack(index,stack_image,stack_images):
if index >= len(sys.argv):
# If passed by last index, save merged image
global stack_count
stack_count += 1
stack_image.save("./merged/" + str(stack_count) + ".png","PNG")
else:
# Else construct new image from the image passed, and paste ontop of it
for image in stack_images[index]:
new_stack_image = Image.new("RGBA", (stack_image.size[0], stack_image.size[1]))
new_stack_image.paste(stack_image, (0,0))
new_stack_image.paste(image, (0,0), image)
# Iterate the next list of stack images
iter_stack(index + 1, new_stack_image, stack_images)
# Iterate all base images and construct new merged images from the stack images
for base_image in base_images:
stack_image = Image.new("RGBA", (base_image.size[0], base_image.size[1]))
stack_image.paste(base_image, (0,0))
iter_stack(0,stack_image,stack_images)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment