如何用Python在图片上显示乌尔都语连字?当前仅显示单个字母
解决Python PIL显示乌尔都语连字问题
PIL的ImageDraw.text原生不支持乌尔都语这类需要复杂字形组合(连字)和从右到左排版的脚本,所以会出现只显示单个字母的情况。要解决这个问题,需要借助arabic_reshaper和python-bidi两个库来处理文本:
步骤1:安装依赖库
pip install python-bidi arabic-reshaper
步骤2:修改代码处理文本
将你的代码修改为以下形式,先对乌尔都语文本进行字形整形和方向校正:
from PIL import Image, ImageFont, ImageDraw import arabic_reshaper from bidi.algorithm import get_display text_string = 'تصوير' # 处理乌尔都语文本:先整形生成连字,再校正从右到左的显示方向 reshaped_text = arabic_reshaper.reshape(text_string) bidi_text = get_display(reshaped_text) img = Image.new('RGB', (200, 150), color='black') # 添加黑色背景,方便查看白色文字 draw = ImageDraw.Draw(img) font = ImageFont.truetype('C:\\Windows\\Nafees Nastaleeq Urdu Font\\Nafees Nastaleeq(Updated).ttf', 50) draw.text((25, 40), bidi_text, fill='white', font=font) img.show()
说明
arabic_reshaper.reshape():将乌尔都语的单个字符转换为符合连字规则的字形组合get_display():处理从右到左的文本排版方向,确保字符顺序正确显示
运行修改后的代码,就能看到正确的乌尔都语连字显示了。
内容的提问来源于stack exchange,提问作者fatima
相关产品推荐
相关产品推荐

