Skip to content

Instantly share code, notes, and snippets.

@jaekookang
Created January 15, 2025 03:36
Show Gist options
  • Save jaekookang/80f267c980a75911a1a24ba7b0804b9f to your computer and use it in GitHub Desktop.
Save jaekookang/80f267c980a75911a1a24ba7b0804b9f to your computer and use it in GitHub Desktop.
Combine two images vertically as save as a png file (python)
'''Combine two images vertically
- arg1 file will be on top while arg2 will be at the bottom
- arg1's width will be the reference to resize arg2 if arg2 has different width
- output file will be saved in the directory of arg1 as "merged.png"
2025-01-15 jkang first created
'''
import os
import sys
from PIL import Image
NEW_FILE = 'merged'
def check_files(filename):
if not os.path.exists(filename):
raise Exception(f'{filename} does not exists')
def main(img1_file, img2_file, fileid):
check_files(img1_file)
check_files(img2_file)
print(f'file1: {img1_file}')
print(f'file2: {img2_file}')
if not fileid:
fileid = NEW_FILE
img1 = Image.open(img1_file)
img2 = Image.open(img2_file)
ref_width = img1.width
if img1.width != img2.width:
target_height = int(img2.height * (ref_width/img2.width))
print(f'target size: w={ref_width} x h={target_height}')
img2 = img2.resize((ref_width, target_height), Image.Resampling.LANCZOS)
img_merge = Image.new(img1.mode, (img1.width, (img1.height+img2.height)))
img_merge.paste(img1, (0, 0))
img_merge.paste(img2, (0, img1.height))
filepath = os.path.abspath(img1_file)
filepath = os.path.dirname(filepath)
newfile = os.path.join(filepath, fileid+'.png')
try:
img_merge.save(newfile)
print(f'{newfile} is created')
except Exception as e:
print('ERROR OCCURRED:')
print(e)
if __name__ == '__main__':
img1_file = sys.argv[1]
img2_file = sys.argv[2]
fileid = sys.argv[3]
main(img1_file, img2_file, fileid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment