粘贴没有添加 python 黑色背景的图像
Pasting image with no black background added with 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")
您需要指定遮罩,因此黑色部分不会被渲染。
见 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.
最后一部分应该是你的情况。
因此在您的情况下,您可以使用 im.paste(mouse, (40,40), mouse)
,因为该图像已经有一个 alpha 通道
编辑:
显然问题与格式 .cur
有关。如果您输入 mouse.getbands()
,它将 return (R, G, B)
,因此是 ValueError
。
您可以将 .cur
文件转换为带有 alpha 通道的 .png
,但是我也得到了以下工作:
mouse_mask = mouse.convert("L")
im.paste(mouse, (40,40), mouse_mask)
我正在尝试截屏并将光标粘贴到它上面,但是当我 运行 我的程序时,结果是光标粘贴有大的黑色背景,有谁知道我怎么能得到黑色背景消失了吗?
这是我的代码:
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")
您需要指定遮罩,因此黑色部分不会被渲染。 见 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.
最后一部分应该是你的情况。
因此在您的情况下,您可以使用 im.paste(mouse, (40,40), mouse)
,因为该图像已经有一个 alpha 通道
编辑:
显然问题与格式 .cur
有关。如果您输入 mouse.getbands()
,它将 return (R, G, B)
,因此是 ValueError
。
您可以将 .cur
文件转换为带有 alpha 通道的 .png
,但是我也得到了以下工作:
mouse_mask = mouse.convert("L")
im.paste(mouse, (40,40), mouse_mask)