无法使用 PIL 和 python 2.7 将文本写入灰度 PNG

gmm*_*mmo 1 python-imaging-library python-2.7 pillow

我正在尝试使用 PIL 并按照此线程在灰度 png 上写一些文本。这看起来很简单,但我不确定我做错了什么。

使用 PIL 在图像上添加文本

然而,当我尝试这样做时,draw.text函数就死了:

from PIL import Image, ImageDraw, ImageFont
img = Image.open("test.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("open-sans/OpenSans-Regular.ttf", 8)
# crashes on the line below:
draw.text((0, 0), "Sample Text", (255, 255, 255), font=font)
img.save('test_out.png')
Run Code Online (Sandbox Code Playgroud)

这是错误日志:

"C:\Python27\lib\site-packages\PIL\ImageDraw.py", line 109, in _getink
ink = self.draw.draw_ink(ink, self.mode)
TypeError: function takes exactly 1 argument (3 given)
Run Code Online (Sandbox Code Playgroud)

谁能指出我的问题?

gmm*_*mmo 8

问题是 png 是 8 位灰度。为了能够在 8 位图像上绘制,我必须在 draw.text 调用中使用单一颜色。换句话说:

# this works only for colored images
draw.text((0, 0), "Sample Text", (255, 255, 255), font=font)

# 8-bit gray scale , just pass one value for the color
# 0 = full black, 255 = full white
draw.text((0, 0), "Sample Text", (255), font=font)
Run Code Online (Sandbox Code Playgroud)

就是这个 :)