简体   繁体   English

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

[英]adding a text over an image in python using imagemagik/PIL

I have a text say "I am doing great". 我有一个文字说“我做得很好”。 I want to put this text over a lovely background which i have generated. 我想把这段文字放在我产生的可爱背景上。 I want to put "I am doing great" over an image "image.jpg" present in the system. 我想在系统中存在的图像"image.jpg"上放置"I am doing great" The starting point of the text should be X, y in pixels. 文本的起点应为X,y(以像素为单位)。

i tried the following snippet, but am having error: Snippet: 我尝试了以下代码段,但出现错误:代码段:

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")

Error: 错误:

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'

seems to be a bug in PIL: http://grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report 似乎是PIL中的错误: http : //grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report

Is there any workaround i can try? 我可以尝试任何解决方法吗?

I ran into this same bug, it seems to be a bug in Pil/Pillow with PNG palette handling. 我遇到了同样的错误,似乎是PNG调色板处理中Pil / Pillow中的错误。 The workaround is to convert your image to RBG before drawing the text: 解决方法是在绘制文本之前将图像转换为RBG:

img = img.convert('RGB')

Look at the text method of the ImageDraw module (top Google hit for 'pil text'.) You'll also need the ImageFont module, which sports relevant example code: 查看ImageDraw模块text方法(Google在“ pil text”中排名最高)。您还需要ImageFont模块,该模块具有相关的示例代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM