[Python] Combine several images horizontally with Python

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to horizontally combine some JPEG images in Python.

    Problem


    I have 3 images - each is 148 x 95 - see attached. I just made 3 copies of the same image - that is why they are the same.

    [​IMG][​IMG][​IMG]

    My attempt


    I am trying to horizontally join them using the following code:

    from PIL import Image

    list_im = ['Test1.jpg','Test2.jpg','Test3.jpg']

    # creates a new empty image, RGB mode, and size 444 by 95
    new_im = Image.new('RGB', (444,95))

    for elem in list_im:
    for i in xrange(0,444,95):
    im=Image.open(elem)
    new_im.paste(im, (i,0))
    new_im.save('test.jpg')


    However, this is producing the output attached as test.jpg.

    [​IMG]

    Question


    Is there a way to horizontally concatenate these images such that the sub-images in test.jpg do not have an extra partial image showing?

    Additional Information


    I am looking for a way to horizontally concatenate n images. I would like to use this code generally so I would prefer to:

    • not to hard-code image dimensions, if possible
    • specify dimensions in one line so that they can be easily changed

    Continue reading...

Compartilhe esta Página