Adding text over image in python using imagemagik / PIL

I have a text that says, "I'm fine." I want to put this text in the beautiful background that I created. I want to put "I am doing great"on top of the 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 I got an error: Excerpt:

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 like a bug in PIL: http://grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report

Is there a workaround I can try?

+5
source share
2 answers

, , Pil/Pillow PNG. , RBG :

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

text ImageDraw ( Google " ".) ImageFont, :

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

All Articles