BytesIO 用黑色背景替换 PNG 文件中的透明度

BytesIO replaces transparency in PNG files with black background

我想在 'image' 变量中保持透明背景。

如果我写入文件,图像看起来不错。我的意思是图片有透明背景。

with urllib.request.urlopen(request) as response:
     imgdata = response.read()
     with open("temp_png_file.png", "wb") as output:
         output.write(imgdata)

但是,如果我将图像数据保存在 BytesIO 中,透明背景就会变成黑色背景。

with urllib.request.urlopen(request) as response:
     imgdata = response.read()
ioFile = io.BytesIO(imgdata) 
img = Image.open(ioFile)
img.show()

(以上代码段,img.show 行显示黑色背景的图像。)

如何在 img 变量中保留透明图像对象?

两件事...


首先,如果您希望并期望在使用 Pillow 打开文件时出现 RGBA 图像,最好将您得到的任何内容转换为该图像 - 否则您最终可能会尝试显示调色板索引而不是 RGB值:

所以改变这个:

img = Image.open(ioFile)

对此:

img = Image.open(ioFile).convert('RGBA')

其次,OpenCVimshow()无法处理透明度,所以我倾向于使用Pillowshow() 方法代替。像这样:

from PIL import Image

# Do OpenCV stuff
...
...

# Now make OpenCV array into Pillow Image and display
Image.fromarray(numpyImage).show()