根据
https://github.com/python-pillow/Pillow/issues/6788
,这就是图像变为黑色的原因:
P模式的理念是有一个多达256种颜色的调色板,图像中的每个像素都是这些颜色中的一种。tobytes()只写出图像像素的索引,而不是调色板。因此,图像变成黑色是因为当它将这些索引转换回图像时,没有调色板来告诉它每个像素是什么颜色。
该问题列出了几种替代方案:
-
您可以单独保存调色板,然后将其应用于最后的新图像。
-
您可以将图像从P转换为RGB或RGBA。
-
您可以将图像保存为特定的图像格式(例如PNG),然后从中加载回图像。
对我来说,第二个选项看起来是最简单的,所以让我们实现它:
image_path = "aJpWQ.png"
img = Image.open(image_path)
width, height = img.size
converted = img.convert("RGBA")
image_data = converted.tobytes()
# insert transformations here
image = Image.frombytes('RGBA', (width, height), image_data)