Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 server:

font_text = ImageFont.load('helvR24.pil')
draw.text((0, 0), 'Текст на русском', font=font_text)

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

On 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 doesn't display Russian characters ('squares' or dummy characters are displayed instead). I think it doesn't work on Development environment since most probably helvR24.pil doesn't contain Russian characters (don't know how to check it). But HelveticaRegular.ttf surely has it. I also checked that my .py file has геа-8 encoding. And it doesn't display Russian characters even with default font:

draw.text((0, 0), 'Текст на русском', font=ImageFont.load_default())

What else should I try / verify? I've looked thru https://stackoverflow.com/a/18729512/604388 - it doesn't help.

like image 985
LA_ Avatar asked Sep 22 '13 10:09

LA_


People also ask

Does PIL work in Python 3?

If you are on Python3 you can also use the library PILasOPENCV which works in Python 2 and 3. Function api calls are the same as in PIL or pillow but internally it works with OpenCV and numpy to load, save and manipulate images.

How do I run a PIL in Python?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).


1 Answers

I had a similar issue and solved it.

There are a couple things you have to be careful about:

  1. Ensure that your strings are interpreted as unicode, either by importing unicode_literarls from _____future_____ or by prepending the u to your strings
  2. 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

enter image description here

like image 177
JackNova Avatar answered Sep 19 '22 11:09

JackNova