代码之家  ›  专栏  ›  技术社区  ›  Hassan Baig Altons

用枕头画草书

  •  0
  • Hassan Baig Altons  · 技术社区  · 7 年前

    Ubuntu 14.04 LTS 机器 Pillow 4.2.1

    我已经通过 ImageDraw PIL (实际代码在本问题末尾)

    我的代码适用于英语、法语或西班牙语等语言。

    但不是为了 自然草书 阿拉伯语、波斯语或乌尔都语。在这种情况下,它会分别绘制每个字母。例如。 فارسی (波斯语)绘制为:

    enter image description here

    注意,我安装了 sudo apt-get install ttf-mscorefonts-installer 并尝试了 /fonts/truetype/msttcorefonts/Arial.ttf

    某人 advised me 确保我使用的字体 . 我的理解是 Arial 确实支持连字,但问题仍然存在。

    我的问题是: 我应该如何解决此问题?我的代码必须支持自然草书语言,如阿拉伯语、波斯语或乌尔都语。


    代码:

    from PIL import ImageDraw
    draw = ImageDraw.Draw(img)
    base_width, base_height = img.size
    y = 2
    for line in lines:
        width, height = font.getsize(line)
        x = (base_width - width) / 2
        text_with_stroke(draw,x,y,line,font,fillcolor,shadowcolor)
        y += height
    

    text_with_stroke 简单来说就是:

    def text_with_stroke(draw,width,height,line,font,fillcolor,shadowcolor):
        draw.text((width-1, height), line, font=font, fill=shadowcolor)
        draw.text((width+1, height), line, font=font, fill=shadowcolor)
        draw.text((width, height-1), line, font=font, fill=shadowcolor)
        draw.text((width, height+1), line, font=font, fill=shadowcolor)
        draw.text((width, height), line, font=font, fill=fillcolor)
    

    简而言之,考虑到字体大小和底层图像大小,该代码将任何给定的文本分成单独的行。然后,它迭代地在图像上绘制每行文本。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Hassan Baig Altons    7 年前

    这个问题的最佳答案已经在这篇相当优秀的SO帖子上解决了: https://stackoverflow.com/a/25727238/4936905

    本质上,这里需要两个Python库: BiDi Arabic Reshaper

    那是 pip install python-bidi pip install git+https://github.com/mpcabd/python-arabic-reshaper text 在通过 PIL :

    reshaped_text = arabic_reshaper.reshape(line)
    final_text = get_display(reshaped_text)
    
    draw.text((width-1, height), final_text, font=font, fill=shadowcolor)
    draw.text((width+1, height), final_text, font=font, fill=shadowcolor)
    draw.text((width, height-1), final_text, font=font, fill=shadowcolor)
    draw.text((width, height+1), final_text, font=font, fill=shadowcolor)
    draw.text((width, height), final_text, font=font, fill=fillcolor)