How to use Unicode characters with PIL?

I would like to add Russian text to the image. I am using PIL 1.1.7 and Python 2.7 on a Windows computer. Since the PIL is compiled without the libfreetype library , I use the following on the development server:

font_text = ImageFont.load('helvR24.pil') draw.text((0, 0), '  ', font=font_text) 

( helvR24.pil taken from http://effbot.org/media/downloads/pilfonts.zip )

In a production environment, I do the following:

 font_text = ImageFont.truetype('HelveticaRegular.ttf', 24, encoding="utf-8") draw.text((0, 0), '  ', font=font_text) 

(tried to use unic , cp-1251 instead of utf-8 )

In both cases, it does not display Russian characters (instead, squares or dummy characters are displayed). I think this does not work in the development environment, since most likely helvR24.pil does not contain Russian characters (I donโ€™t know how to check this). But HelveticaRegular.ttf surely has this. I also verified that my .py file is gea-8 encoded. And it does not display Russian characters even with the default font:

 draw.text((0, 0), '  ', font=ImageFont.load_default()) 

What else should I try / check? I have looked through https://stackoverflow.com/a/464629/2127/ - this does not help.

+6
source share
2 answers

I had a similar problem and it was resolved.

There are a few things you should be careful about:

  1. Make sure your lines are interpreted as unicode, either by importing unicode_literarls from _____future_____, or by adding u to your lines
  2. Make sure you use a Unicode font, there are some free ones here: Unicode open source fonts. I suggest the following: 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 are the results

enter image description here

+5
source

Can you check your TTF file? I suspect that it does not support the characters you want to draw.

On my computer (Ubuntu 13.04) this sequence creates 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() 

Nb When I did not specify unicode ( u'...' ), the result was mojibake .

+2
source

Source: https://habr.com/ru/post/954341/


All Articles