Re: Putting a unicode string on an ImageDraw canvas

Thomas Larsen Wessel <[email protected]>
Newsgroups gmane.comp.python.image
Message-ID <[email protected]>
Thanks :)

Here is an example that shows how both draw.text and draw.textsize works, as
long as a unicode-supported font is supplied. It also shows how to get the
text size directly from the font object.

import ImageFont, Image, ImageDraw

s = u'\u0623\u0636\u0641'

font = ImageFont.truetype('/host/WINDOWS/Fonts/tahoma.ttf', 12,
encoding='unic')
print font.getsize(s) # no problem, works fine

im = Image.new('RGB', (200,200))
draw = ImageDraw.Draw(im)
print draw.textsize(s, font=font) #fails




Thomas





On Mon, Jan 10, 2011 at 2:27 PM, Fredrik Lundh <[email protected]>wrote:

> 2011/1/10 Thomas Larsen Wessel <[email protected]>:
> > People are telling me that PIL supports unicode strings, does it? And if
> > yes, why does the following not work:
> >
> > import ImageFont, Image, ImageDraw
> > s = u'\u0623\u0636\u0641'
> > im = Image.new('RGB', (200,200))
> > draw = ImageDraw.Draw(im)
> > draw.text((40,40), s) #fails
> >
> > It results in the following exception:
> >
> > Traceback (most recent call last):
> >   File "buffer.py", line 9, in <module>
> >     draw.text((40,40), s) #fails
> >   File "/usr/lib/python2.6/dist-packages/PIL/ImageDraw.py", line 267, in
> > text
> >     mask = font.getmask(text, self.fontmode)
> > UnicodeEncodeError: 'ascii' codec can't encode characters in position
> 0-2:
> > ordinal not in range(128)
> >
> > So how, do I put this unicode string on the canvas?
>
> You'll need a font that supports Unicode, which the crappy default
> bitmap font doesn't.  Use the ImageFont module to load a suitable
> TrueType font.
>
> </F>
>

_______________________________________________
Image-SIG maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/image-sig
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.