python - 在python中的图像中插入波斯文字,UnicodeEncodeError: 'latin-1'编解码器无法在位置0-4处编码字符:序数不在范围内(256)

标签 python opencv python-imaging-library

我想在图像中插入波斯文字,
我正在使用此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

最佳答案

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阿拉伯语(免费用于个人和商业用途)。
  • 关于python - 在python中的图像中插入波斯文字,UnicodeEncodeError: 'latin-1'编解码器无法在位置0-4处编码字符:序数不在范围内(256),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64422332/

    相关文章:

    Python 将年中的某一天转换为轴上的月份

    OpenCV 3.1.0 找到 CUDA 7.5 而不是 8.0

    python - 如何将 PIL 图像转换为 NumPy 数组?

    python - 在 Python 中计算两个图像之间的绝对差之和的最快方法是什么?

    Python - 通过键显示值的字典

    python - 错误 :_pickle. PicklingError: Can't pickle <function <lambda> at 0x0000002F2175B048>: attribute lookup <lambda> on __main__ failed

    python - NumPy:3 字节、6 字节类型(又名 uint24、uint48)

    OpenCV 转换为更小的数据类型 : Max, 或截断/溢出?

    等高线的opencv区域

    python - 如果没有图像处理Python库(Pillow和cv2)无法读取,如何解码这个二进制图像文件?