Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Chinese characters to images
-
I would like to modify the built in Cards.py game to display a series of Chinese characters rather than the animal pictures. I have successfully changed it to use numbers and letters so I thought it would be simple to go further and use foreign characters.
In the code below I have the Chinese character for the number 5.
I print it to the console in three different ways and all three work fine.
When I try to convert the character to an image (which works fine with characters such as 'a', 'G" and '4') it returns an image with unexpected characters, even to the point that the second image differs from the other two.
I have selected a font that should contain Simplified Chinese characters and I even tried using the same font as that used by the console (commented out) on the assumption that if it displayed correctly on the console the font should contain the desired character.
What is wrong? Is the PIL ImageDraw.Draw.text incapable of handling unicode characters?
#coding: utf-8 from PIL import Image, ImageFont, ImageDraw def TextToImage(text_in,width,height,font_in): pil_image = Image.new("RGBA",(width,height),(0,0,0,0)) draw = ImageDraw.Draw(pil_image) text_width, text_height = draw.textsize(text_in,font=my_font) draw.text(((width/2)-(text_width/2), (height/2)-(text_height/2)), text_in, "black", font=font_in) return pil_image print '五' print u'\u4e94'.encode('utf_8') ch = u'\u4e94'.encode('utf_8') print ch my_font = ImageFont.truetype("STHeitiSC-Light", 72) #my_font = ImageFont.truetype("DejaVuSansMono", 72) my_image = TextToImage('五',300,96,my_font) my_image.show() my_image = TextToImage(u'\4e94'.encode('utf_8'),300,96,my_font) my_image.show() my_image = TextToImage(ch,300,96,my_font) my_image.show()
-
Python3 is much more Unicode-ready that Python2. Always put the u in front of string literals that contain Unicode characters.
print(type('五'), type(u'五')) # (<type 'str'>, <type 'unicode'>)
Adding the u to this line will get the first image to work properly.
my_image = TextToImage(u'五', 300, 96, my_font)
This modification will get both the first and last images to work properly.
def TextToImage(text_in,width,height,font_in): print(type(text_in)) text_in = unicode(text_in) # switch from str to unicode print(type(text_in))
The middle image is left as an exersize for the reader.
-
Thanks ccc that's solved my problem.
I now have cards with the Chinese numbers from 1 to 8 as an option in the game.