【问题标题】:Can't write text to grayscale PNG using PIL and python 2.7无法使用 PIL 和 python 2.7 将文本写入灰度 PNG
【发布时间】:2017-09-28 23:42:46
【问题描述】:

我正在尝试使用 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)

谁能指出我的问题?

【问题讨论】:

  • 它适用于我在 macOS 上的 Python 2.7.13 和 Pillow 4.1.0,尽管我使用 img = Image.new("RGB", (300, 300)) 而不是打开现有图像。完整的追溯是什么?您使用的是哪个版本的 Pillow?
  • @Hugo 看到我的回答。我不得不做一些黑客攻击:)

标签: python-2.7 python-imaging-library pillow


【解决方案1】:

问题在于 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)

就是这样:)

【讨论】:

    猜你喜欢
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2011-09-15
    • 1970-01-01
    • 2017-07-21
    • 2015-11-06
    相关资源
    最近更新 更多