Why does PIL fail to merge 2 images in my code?

喜夏-厌秋 提交于 2019-12-31 07:10:41

问题


I am trying to combine 2 images into a larger one with Image.paste function. I start by creating an image that can hold both images, and then paste in the 2 images:

wrapper = Image.new("I", (width, height+textHeight));

if placement=="bottom":
 wrapper.paste(img1); 
 wrapper.paste(textImage, (0, height, width, textHeight));
else:
 wrapper.paste(textImage);
 wrapper.paste(img1, (0,textHeight));

Then I get this error every time:

 File "C:\Python27\lib\site-packages\PIL\Image.py", line 1127, in paste
    self.im.paste(im, box)
ValueError: images do not match

I am very sure that the sizes of the images are correct, and the wrapper image can hold both images. The only way to avoid this error is to make the 3 images (wrapper and 2 components) same size, and paste from (0,0).

I am at my wits' end, please help!


回答1:


There are two possible issues.

  1. Are you sure your 4-tuple (0, height, width, textHeight) is correct? It should be (left, upper, right, lower) pixel coordinates. In this case the pasted image must match the size of the region, and I think this is where your error lies. Alternatively you can give a 2-tuple giving just the upper left corner of where you want to paste the picture. See: http://effbot.org/imagingbook/image.htm

  2. Are you sure that height, width, textHeight are ints and not floats?

You could try something like this:

x, y = img1.size
wrapper.paste(textImage,(0,height,x,y))


来源:https://stackoverflow.com/questions/20297659/why-does-pil-fail-to-merge-2-images-in-my-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!