简体   繁体   中英

Merge Images In Python

I am trying to merge two images together if their sizes are equal. Can anyone help me please? This is what I got so far....

import PIL
from PIL import Image as img
x = img.open('index.jpg')
w1, h1 = x.size
print('Image 1 =',w1,'x',h1)

y = img.open('index2.jpg')
w2, h2 = y.size
print('Image 2 =',w1,'x',h1)

if x.size == y.size :
    print('Their size is equal.')
    height = max(h1,h2)
    width = w1 + w2
    z = img.new("RGB",(width,height))
    z.paste(x)
    #z.paste(y)
    z.show()

else:
    print('Their size is not equal.')

what can i do to paste the second image next to the first image?

The .paste(..) function allows you to specify the box parameter to specify the location.

You thus can paste the second image with:

import PIL
from PIL import Image as img
x = img.open('img1.jpg')
w1, h1 = x.size
print('Image 1 =',w1,'x',h1)

y = img.open('img2.jpg')
w2, h2 = y.size
print('Image 2 =',w1,'x',h1)

if x.size == y.size :
    print('Their size is equal.')
    z = img.new("RGB",(w1 + w2,h1))
    z.paste(x)
    z.paste(y)
    z.show()
else:
    print('Their size is not equal.')

Note that since the sizes are equal the height is just h1 .

You can relax the constraint of the sizes, since if the heights is the same, this will work as well, except that the image is not split in half if the widths are not the same:

import PIL
from PIL import Image as img
x = img.open('img1.jpg')
w1, h1 = x.size
print('Image 1 =',w1,'x',h1)

y = img.open('img2.jpg')
w2, h2 = y.size
print('Image 2 =',w1,'x',h1)

if :
    print('Their size is equal.')
    z = img.new("RGB",(w1 + w2,h1))
    z.paste(x)
    z.paste(y, box=(w1, 0))
    z.show()
else:
    print('Their size is not equal.')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM