How To Use Unicode Characters With Pil?
I would like to add Russian text to the image. I use PIL 1.1.7 and Python 2.7 on Windows machine. Since PIL compiled without libfreetype library, I use the following on development
Solution 1:
I had a similar issue and solved it.
There are a couple things you have to be careful about:
- Ensure that your strings are interpreted as unicode, either by importing unicode_literarls from _____future_____ or by prepending the u to your strings
- Ensure you are using a font that is unicode,there are some free here: open-source unicode typefaces I suggest this: dejavu
here is the code:
#!/usr/bin/python# -*- coding: utf-8 -*-from PIL import Image, ImageDraw, ImageFont, ImageFilter
#configuration
font_size=36
width=500
height=100
back_ground_color=(255,255,255)
font_size=36
font_color=(0,0,0)
unicode_text = u"\u2605" + u"\u2606" + u"Текст на русском"
im = Image.new ( "RGB", (width,height), back_ground_color )
draw = ImageDraw.Draw ( im )
unicode_font = ImageFont.truetype("DejaVuSans.ttf", font_size)
draw.text ( (10,10), unicode_text, font=unicode_font, fill=font_color )
im.save("text.jpg")
here is the results
Solution 2:
Can you examine your TTF file? I suspect that it doesn't support the characters you want to draw.
On my computer (Ubuntu 13.04), this sequence produces the correct image:
ttf=ImageFont.truetype('/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', 16)
im = Image.new("RGB", (512,512), "white")
ImageDraw.Draw(im).text((00,00), u'Текст на русском', fill='black', font=ttf)
im.show()
N.b. When I didn't specify unicode (u'...'
), the result was mojibake.
Post a Comment for "How To Use Unicode Characters With Pil?"