问题
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.
回答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

回答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.
来源:https://stackoverflow.com/questions/18942605/how-to-use-unicode-characters-with-pil