Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. The starting point of the text should be X, y in pixels.

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

Is there any workaround i can try?

like image 884
user993563 Avatar asked Feb 14 '12 12:02

user993563


2 Answers

I ran into this same bug, it seems to be a bug in Pil/Pillow with PNG palette handling. The workaround is to convert your image to RBG before drawing the text:

img = img.convert('RGB')
like image 67
Jesse Crocker Avatar answered Sep 23 '22 13:09

Jesse Crocker


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:

import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 10), "hello", font=font)
like image 33
badp Avatar answered Sep 24 '22 13:09

badp