python - 在 Python 的 PIL 中渲染波斯语(波斯语)单词

标签 python python-3.x fonts python-imaging-library persian

我正在尝试根据波斯语(波斯语)文本制作图像。
我正在为 Python3 使用 PIL。这是我的代码:

from PIL import Image, ImageFont, ImageDraw
text = "خطاب"
image = Image.new("RGBA", (100,100), (255,255,255))
font = ImageFont.truetype("FreeFarsiMono.ttf", 60, encoding='unic')
draw = ImageDraw.Draw(image)
draw.text((0,0), text, (0,0,0), font=font)
image.save("Test.png")
image.show() 

但是,当我运行代码时,我得到了一些带有问号的矩形框,而不是文本图像!
我将不胜感激。

最佳答案

首先,您必须设置源代码:

# -*- coding: utf-8 -*-

然后你必须解码你的文本:
text = text.decode('utf-8')

你的最终代码应该是这样的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PIL import Image, ImageFont, ImageDraw

text = "ﻡﻼﺳ"
text = text.decode('utf-8')
image = Image.new("RGBA", (100,100), (255,255,255))
font = ImageFont.truetype("yekan.ttf", 45, encoding='unic')
draw = ImageDraw.Draw(image)
draw.text((0,0), text, (0,0,0), font=font)
image.save("Test.png")
image.show()

注意如果你把你的字母分开,你会转换它们;例如您可以使用 awebfont来解决这个问题。

输出:

Test.png

关于python - 在 Python 的 PIL 中渲染波斯语(波斯语)单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861260/

相关文章:

python - 使用 asyncio_mongo 在 mongodb 上插入

css - 未获取@font-face 中使用的字体文件

android - 波斯字体未应用于 android WebView

python - selenium - 如何在框中输入值?

python - 将图像上传到 Google App Engine 并与用户共享图像

python - 有没有一种方法可以将 PyUnicodeObject 变量转换为 PyObject 类型?

ios - 如何让用户从应用程序内的字体、大小和颜色列表中进行选择?

python - 使用 Pytorch 或 Python 将包含图像的目录拆分为子文件夹

php - 将网站导出到 XML 页面

python - 所以我在制作角色动画时遇到了麻烦,而且我是 python 的新手。我不断收到此错误,但我不明白