Search code examples
pythonpython-imaging-library

How merge image with python pillow into center of an another image?


enter image description hereI have two images. I want to merge one image into the other but it has to be perfectly in the middle?

im1 = Image.open('image1.png')
im2 = Image.open('image2.png')
back_im = im1.copy()

#location of image

back_im.paste(im2,(370, 330))
back_im.save('newimg.png', quality=95)

Solution

  • Solution:

    You have to calculate the center point of the larger image, then the top left position of the inner image is offset it 1/2 of it's height and width. For example

    # Get dimensions of each image
    width1, height1 = im1.size
    width2, height2 = im2.size
    
    # Find center pixel of outer image
    center_x, center_y = (width1/2), (height1/2)
    
    # Offset inner image to align its center
    im2_x = center_x - (width2/2)
    im2_y = center_y - (height2/2)
    
    # Paste inner image over outer image
    back_im = im1.copy()
    back_im.paste(im2,(im2_x, im2_y))