5

我有一个文字说“我做得很好”。我想把这段文字放在我生成的可爱背景上。 我想将"I am doing great"放在系统中的图像"image.jpg"上。 文本的起点应该是X,y(以像素为单位)。使用imagemagik/PIL在python中的图像上添加文本

我尝试下面的代码片段,但我有错误: 段:

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的错误: http://grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report

有任何解决方法,我可以尝试?

回答

1

看的text方法the ImageDraw module(上谷歌命中“PIL文本”。)您还需要在ImageFont模块,它带来了相关的例子代码:

import ImageFont, ImageDraw 
draw = ImageDraw.Draw(image) 
font = ImageFont.truetype("arial.ttf", 15) 
draw.text((10, 10), "hello", font=font) 
+0

这提到如何绘制,而不是如何写文本。你想画信吗?我不用typographicfy使用pil。 – user993563 2012-02-14 12:34:51

+3

恐怕我真的不明白将图像绘制到图像上并将文本写入图像的区别。 – badp 2012-02-14 12:38:25

+0

更新,请chk编辑部分。 – user993563 2012-02-14 13:30:23

4

我遇到了同样的bug ,它似乎是Pil /枕头和PNG调色板处理中的一个错误。解决方法是在绘制文本之前将图像转换为RBG:

img = img.convert('RGB') 
+0

谢谢!我在同样的问题(或非常类似的问题)中挣扎,并且转换图像的技巧。 – jlliagre 2015-06-24 21:32:09

+0

像一个魅力工作! – repzero 2016-06-30 02:23:39