Merge Images Horizontally and Vertically Using Python

There are several websites that have applications/tools to merge images online. Sometimes it becomes very irritating if websites put limitations on the number of images that you can combine or on the number of merged files. I faced this problem when a website did not allow me to create more than two merged files. So, I wrote the following code to help myself. This is a basic code to merge images horizontally or vertically. You can modify it to change size, resolution, etc.

import numpy as np
from PIL import Image

def merge_images_horizontally(imgs):
    '''
    This function merges images horizontally.
    '''
    #create two lists - one for heights and one for widths
    widths, heights = zip(*(i.size for i in imgs))
    width_of_new_image = sum(widths)
    height_of_new_image = min(heights) #take minimum height
    # create new image
    new_im = Image.new('RGB', (width_of_new_image, height_of_new_image))
    new_pos = 0
    for im in imgs:
        new_im.paste(im, (new_pos,0))
        new_pos += im.size[0] #position for the next image
    new_im.save('data/final1.jpg') #change the filename if you want


def merge_images_vertically(imgs):
    '''
    This function merges images vertically
    '''
    #create two lists - one for heights and one for widths
    widths, heights = zip(*(i.size for i in imgs))
    width_of_new_image = min(widths)  #take minimum width
    height_of_new_image = sum(heights)
    # create new image
    new_im = Image.new('RGB', (width_of_new_image, height_of_new_image))
    new_pos = 0
    for im in imgs:
        new_im.paste(im, (0, new_pos))
        new_pos += im.size[1] #position for the next image
    new_im.save('data/final2.jpg') #change the filename if you want


def main():
    '''
    Start of the code.
    '''
    # open images files
    imgs = [Image.open(im) for im in list_im]
    ###merge images horizontally
    merge_images_horizontally(imgs)
    ###merge images vertically
    merge_images_vertically(imgs)


#list of images
list_im = ['data/photo1.jpg', 'data/photo2.jpg'] #change it to use your images

if __name__ == '__main__':
    '''
    This program merges images horizontally and Vertically.
    '''
    main()

Here are the outputs of the above code: 1. merged horizontally, 2. merged vertically

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.