Sunday, June 27, 2010

Add text on image with PIL module.

It's easy to create images with PIL module.
This is the script:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf",25)
img=Image.new("RGBA", (200,200),(120,20,20))
draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(255,255,0),font=font)
draw = ImageDraw.Draw(img)
draw = ImageDraw.Draw(img)
img.save("a_test.png")
The only error that can occur is not to find the font.
In this case you must change the code line:
font = ImageFont.truetype("/usr/share/fonts/dejavu/DejaVuSans.ttf",25)
Here is the result script:

6 comments:

  1. I didn't have photoshop but needed to add text to an image real fast (for PSP--Pretty Stupid Privacy--encryption)

    For Mac fonts I just grabbed something like /System/Library/Fonts/AppleGothic.ttf

    worked great, thanks!

    ReplyDelete
  2. I want to add kannada text over an image..I am able to add single unicode valued character but not the compound characters.please let me know the ans.

    ReplyDelete
  3. how can i break the text line if i want to get this:
    This is
    a text

    using single draw.text()
    ???

    ReplyDelete
  4. Всеволод, here you go

    http://stackoverflow.com/questions/7698231/python-pil-draw-multiline-text-on-image

    ReplyDelete