在python中的图像中插入波斯语文本,UnicodeEncodeError:“latin1”编解码器无法对位置04中的字符进行编码:序号不在范围内(256)

2024-09-28 22:09:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在图像中插入波斯语文本, 我使用这个link使用这个链接

代码如下:

import arabic_reshaper

from bidi.algorithm import get_display

from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

#fontFile = "/Users/amirreza/pil/Sahel.ttf"

imageFile = r'/content/flower_1.jpg'

#font = ImageFont.truetype(fontFile, 18)
image = Image.open(imageFile)

text = "سلام ایران"
reshaped_text = arabic_reshaper.reshape(text)    # correct its shape
bidi_text = get_display(reshaped_text)           # correct its direction

draw = ImageDraw.Draw(image)
draw.text((0, 0), bidi_text, (255,255,255))
draw = ImageDraw.Draw(image)

image.save("output.png")

但这种错误会发生:

enter coUnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-4: ordinal not in range(256)de here

Tags: textfromimageimportgetpildisplaydraw
1条回答
网友
1楼 · 发布于 2024-09-28 22:09:35

PIL中的默认字体不支持阿拉伯语字符

您必须加载不支持阿拉伯字符的字体文件:

arabic_font = ImageFont.truetype('ArbFONTS-Ubuntu-Arabic_B.ttf', 40)

它们将其作为参数传递给Drawtext函数:

draw.text((0, 0), bidi_text, (255,255,255), font=arabic_font)

警告在此之后,您的代码将运行,但您需要支持阿拉伯字符的字体,否则您的输出将无法正确显示文本

这两种字体对阿拉伯语字体(imho)有很好的支持:

  • Arial(在Windows上提供。您可能需要Monotype Corporation的许可证才能在程序上使用该字体)
  • Ubuntu阿拉伯语(个人和商业自由使用)

相关问题 更多 >