2017-02-13 63 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

是的,謝謝! –