Writing text with diacritic (“nikud”, vocalization marks) using PIL (Python Imaging Library)

前端 未结 4 1194
南方客
南方客 2020-12-11 03:59

Writing simple text on an image using PIL is easy.

draw = ImageDraw.Draw(img)
draw.text((10, y), text2, font=font, fill=forecolor )

However

4条回答
  •  青春惊慌失措
    2020-12-11 04:36

    funny, after 5 years, and with great help fron @Nasser Al-Wohaibi, I realized how to do it:

    Reversing the text with a BIDI algorithm was needed.

    # -*- coding: utf-8 -*-
    from bidi.algorithm import get_display
    import PIL.Image, PIL.ImageFont, PIL.ImageDraw
    img= PIL.Image.new("L", (400, 200))
    draw = PIL.ImageDraw.Draw(img)
    font = PIL.ImageFont.truetype( r"c:\windows\fonts\arial.ttf", 30)
    t1 = u'סֶפֶר ספר!'
    draw.text( (10,10), 'before BiDi :' + t1, fill=255, font=font)
    
    t2 = get_display(t1)        # <--- here's the magic <---
    draw.text( (10,50), 'after BiDi: ' + t2, fill=220, font=font)
    
    img.save( 'bidi-test.png')
    

    @Nasser's answer has extra value that's probably relevant only to arabic texts (the letters in arabic change shape and connected-ness based on their neiboring letters, in hebrew all letters are separate), so only the bidi part was relevant for this question.

    in the sample result, the 2nd line is the correct form, and correct vocalization marks positioning.

    before and after bidi

    thank you @tzot for help + code snippets

    a-propos:

    samples of different font behavior with Hebrew "nikud". Not all fonts behave the same: sample PIL written, bidi hebrew text, with nikud, in different fonts

提交回复
热议问题