TJ1*_*TJ1 5 python fonts persian python-imaging-library python-3.x
我正在尝试根据波斯语(波斯语)文本制作图像。\n我正在使用适用于 Python3 的 PIL。这是我的代码:
\n\nfrom PIL import Image, ImageFont, ImageDraw\ntext = "\xd8\xae\xd8\xb7\xd8\xa7\xd8\xa8"\nimage = Image.new("RGBA", (100,100), (255,255,255))\nfont = ImageFont.truetype("FreeFarsiMono.ttf", 60, encoding=\'unic\')\ndraw = ImageDraw.Draw(image)\ndraw.text((0,0), text, (0,0,0), font=font)\nimage.save("Test.png")\nimage.show() \nRun Code Online (Sandbox Code Playgroud)\n\n然而,当我运行代码时,我得到一些带有问号的矩形框,而不是文本的图像! \n我将不胜感激。
\n小智 0
首先,您必须设置源的编码:
\n\n# -*- coding: utf-8 -*-\nRun Code Online (Sandbox Code Playgroud)\n\n然后你必须解码你的文本:
\n\ntext = text.decode(\'utf-8\')\nRun Code Online (Sandbox Code Playgroud)\n\n你的最终代码应该是这样的:
\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom PIL import Image, ImageFont, ImageDraw\n\ntext = "\xef\xbb\xa1\xef\xbb\xbc\xef\xba\xb3"\ntext = text.decode(\'utf-8\')\nimage = Image.new("RGBA", (100,100), (255,255,255))\nfont = ImageFont.truetype("yekan.ttf", 45, encoding=\'unic\')\ndraw = ImageDraw.Draw(image)\ndraw.text((0,0), text, (0,0,0), font=font)\nimage.save("Test.png")\nimage.show()\nRun Code Online (Sandbox Code Playgroud)\n\n注意:如果您将字母分开,则需要将它们转换;例如,您可以使用awebfont来解决该问题。
\n\n输出:
\n\n