使用imagemagick/PIL在Python中向图像添加文本

5

我有一个文本,内容是“我很好”。我想把这个文本放在一个我生成的可爱背景上。我想把"I am doing great"放在系统中的图像"image.jpg"上。文本的起始点应该是以像素为单位的X和Y。

我尝试了以下代码段,但出现错误:

import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

font = ImageFont.truetype("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf",40)
text = "Sample Text"
tcolor = (255,0,0)
text_pos = (100,100)

img = Image.open("certificate.png")
draw = ImageDraw.Draw(img)
draw.text(text_pos, text, fill=tcolor, font=font)
del draw

img.save("a_test.png")

错误:

Traceback (most recent call last):
  File "img_man.py", line 13, in <module>
    draw.text(text_pos, text, fill=tcolor, font=font)
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImageDraw.py", line 256, in text
    ink, fill = self._getink(fill)
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImageDraw.py", line 145, in _getink
    ink = self.palette.getcolor(ink)
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImagePalette.py", line 62, in getcolor
    self.palette = map(int, self.palette)
ValueError: invalid literal for int() with base 10: '\xed'

似乎PIL中有一个bug: http://grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report

我能尝试什么解决方法吗?

2个回答

4

我遇到了同样的问题,看起来这是Pil/Pillow在处理PNG调色板时出现的错误。解决方法是在绘制文本之前将图像转换为RGB:

img = img.convert('RGB')

谢谢!我也遇到了同样的(或非常相似的)问题,转换图像解决了这个问题。 - jlliagre

1
看一下 ImageDraw 模块text 方法(在谷歌搜索“pil text”中排名第一)。你还需要 ImageFont 模块,其中包含相关的示例代码:
import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 10), "hello", font=font)

这里提到的是如何绘制,而不是如何编写文本。你想要绘制字母吗?我不建议使用PIL进行排版。 - user993563
3
我担心我不太明白在图像上绘制文本和在图像上写入文本之间的区别。 - badp
@user993563 那个错误信息似乎有点复杂,但我相信它与tcolor有关,因为异常实际发生的位置在ImagePalette.py的第62行(getcolor函数内)。 - badp
似乎PIL库中存在一个bug http://grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report 有没有解决方法? - user993563

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接