使用imagemagik/PIL在python中的图像上添加文本

use*_*563 5 python image-processing python-imaging-library python-2.7

我有一个文字说"我做得很好".我想把这个文本放在我生成的可爱背景上.我想把系统中存在"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")
Run Code Online (Sandbox Code Playgroud)

错误:

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'
Run Code Online (Sandbox Code Playgroud)

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

我可以尝试一下吗?

bad*_*adp 1

查看模块text的方法(Google 搜索结果中的“pil text”。)您还需要该模块,其中包含相关的示例代码:ImageDrawImageFont

import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 10), "hello", font=font)
Run Code Online (Sandbox Code Playgroud)

  • 恐怕我不太明白在图像上绘制文本和在图像上写入文本之间的区别。 (3认同)