首页 > 解决方案 > 为什么 Pillow 通过 ImageDraw 绘图时会反转颜色?

问题描述

我正在尝试将图像粘贴到另一个 8 位/像素(L模式)上,但颜色会反转。如何解决这个问题?示例代码:

icon_bmp2 = Image.open("assets/test_penguin.png")
icon_bmp2 = icon_bmp2.convert("L")
im2 = Image.new('L', (650, 500), 0xFF) # this line cannot be changed
image_draw2 = ImageDraw.Draw(im2)
image_draw2.bitmap((0, 0), icon_bmp2)
im2.save('test.png') # inverted

测试图像来自这里:https ://github.com/GregDMeyer/IT8951/blob/master/test/integration/images/sleeping_penguin.png ,我使用的是 Python 3.7 和 Pillow 7.2.0

标签: pythonpython-imaging-library

解决方案


您应该使用该Image.paste()函数而不是ImageDraw.bitmap()将一个图像的像素粘贴到另一个图像上。它也更易于使用,因为无需创建ImageDraw第一个即可使用它。

from PIL import Image, ImageDraw


icon_bmp2 = Image.open("sleeping_penguin.png")
icon_bmp2 = icon_bmp2.convert("L")

im2 = Image.new('L', (650, 500), 0xFF)  # This line cannot be changed.
im2.paste(icon_bmp2)
im2.save('test2.png')

非反转结果

在此处输入图像描述


推荐阅读