简体   繁体   English

在 Python 中合并图像

[英]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. .paste(..)函数允许您指定box参数来指定位置。

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, box=(w1, 0))
    z.show()
else:
    print('Their size is not equal.')

Note that since the sizes are equal the height is just h1 .请注意,由于大小相等,因此高度仅为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 h1 == h2:
    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.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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