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:

10 comments:

亦妮亦妮 said...

幸福不是一切,人還有責任。.................................................................

Kumar McMillan said...

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!

Shillu said...

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.

Всеволод said...

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

using single draw.text()
???

Bahodir said...

thanks

Bahodir said...

Всеволод, here you go

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

Justin said...

Thank you. A very helpful post. Worked great for my project.

Justin

Anonymous said...

Why do you have two "draw = ImageDraw.Draw(img)" assignments after drawing the text?

Anonymous said...

It's easier to just do a "del draw" rather than creating two new draw objects. I suspect that the removal (or overwriting, in the authors case) causes the draw to "complete", otherwise it is buffered and the image isn't updated.

Curious Explorer said...

Thanks. This helped me a lot :)

Post a Comment