fonttest.py 1006 B

123456789101112131415161718192021222324252627282930
  1. from PIL import Image,ImageDraw,ImageFont
  2. unicode_text = "這是一段中文測試"
  3. #font = ImageFont.truetype("c:/portable/fonts/華康綜藝體.ttf", 40,encoding='big5')
  4. #font = ImageFont.truetype("c:/portable/fonts/華康綜藝體.ttf", 40,encoding='big5')
  5. font = ImageFont.truetype("/var/fonts/adv.ttf", 40,encoding='big5')
  6. text_width, text_height = font.getsize(unicode_text)
  7. canvas = Image.new('RGBA', (500, 500), (255, 0, 0, 0) )
  8. draw = ImageDraw.Draw(canvas)
  9. def myunichchar(unicode_char):
  10. mb_string = unicode_char.encode('big5')
  11. try:
  12. unicode_char = unichr(ord(mb_string[0]) << 8 | ord(mb_string[1]))
  13. except NameError:
  14. unicode_char = chr(mb_string[0] << 8 | mb_string[1])
  15. return unicode_char
  16. text=''
  17. for c in unicode_text:
  18. text+=myunichchar(c)
  19. #text=myunichchar('中')+myunichchar('文')+myunichchar('測')+myunichchar('試')
  20. draw.text((5,5), text, (255, 0, 0), font)
  21. # save the blank canvas to a file
  22. canvas.save("unicode-text.png", "PNG")
  23. canvas.show()