"/>
  简体   繁体   中英

Transparet pixels are being pasted as black in PIL

I paste an image with transparent pixels, but they are black in the final image

img = Image.new('RGBA', (100, 100), "white")

arbol16 = Image.open("arbol16.png")

img.paste(arbol16,( 0, 0, 16, 16))

img.show()

arbol16.png image file:

<code> arbol16.png </ code>图片文件的内容

I think you're (understandably) being confused by what the img.show() is displaying — which I believe is wrong (and may in fact be a bug). On my Windows system a temporary .BMP image is displayed, and it looks like the transparent pixels are black.

<code> img.save()</ code>调用产生的误导性结果

However if you add a line like img.save('arbol16_mod.png') at the end and then view that image file by manually opening it in some image file viewing program, such as Paint, Windows Photo Viewer, or Photoshop, the result is correct.

正确的结果

The paste method does not take into account the alpha of the image it's pasting; you need to add a mask parameter to control that. If the image you're pasting is RGBA you can just pass it twice.

arbol16 = arbol16.convert("RGBA")
img.paste(arbol16, (0, 0, 16, 16), arbol16)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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