2017-02-13 67 views
0

我想截图并将光标粘贴在它上面,但是当我运行我的程序时,结果是光标粘贴了大黑色背景,有人知道我是怎样的可以让黑色背景消失吗?用python添加没有黑色背景的粘贴图像

这是我的代码:

from PIL import Image 

im = Image.open("screenShot.png") 
mouse = Image.open(r"C:\Windows\Cursors\aero_arrow.cur") 
im.paste(mouse, (40,40)) #Drawing the cursor 
im.save("newImage.png") 

回答

0

你需要指定一个面膜,让黑色部分不会被渲染。 见docs

im.paste(image, box, mask)

Same as above, but updates only the regions indicated by the mask. You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values can be used for transparency effects.

Note that if you paste an “RGBA” image, the alpha band is ignored. You can work around this by using the same image as both source image and mask.

半句应该是你的情况。

所以你的情况考虑到该图像已经有一个alpha通道

编辑,你可以使用im.paste(mouse, (40,40), mouse)

显然,问题与格式.cur做。如果您输入mouse.getbands()它将返回(R, G, B),因此ValueError。 您可以在.cur文件到.png转换alpha通道,但是我也得到了以下工作:

mouse_mask = mouse.convert("L") 
im.paste(mouse, (40,40), mouse_mask) 
+0

我以前试过,但得到了ValueError异常的'错误消息:坏透明度mask' –

+0

@EyalS好的,我编辑了我的答案。这是否工作? –

+0

是的,谢谢! –