无法使用 PIL 和 python 2.7 将文本写入灰度 PNG
Can't write text to grayscale PNG using PIL and python 2.7
我正在尝试使用 PIL 并遵循此线程在灰度 png 上写一些文本。看起来很简单,但我不确定我做错了什么。
Add Text on Image using 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')
这是错误日志:
"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)
谁能指出我的问题?
问题是 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)
就是这样:)
我正在尝试使用 PIL 并遵循此线程在灰度 png 上写一些文本。看起来很简单,但我不确定我做错了什么。
Add Text on Image using 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')
这是错误日志:
"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)
谁能指出我的问题?
问题是 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)
就是这样:)