How can I print Hindi sentences(unicode) on image in Python?

前端 未结 3 1262
醉话见心
醉话见心 2021-02-07 04:40

I have a file named \"hindi.txt\". It has contents as follows. I\'m using Python3.5.

कामकाजी महिलाओं के लिए देश में दिल्ली असुरक्षित, सिक्किम सबसे बेहतर: रिपोर्ट         


        
3条回答
  •  抹茶落季
    2021-02-07 04:57

    There seems an open bug for rendering the hindi (Devanagari font) text.

    https://github.com/python-pillow/Pillow/issues/3191

    You may try with some other library like: pyvips (I do not find the API very intuitive, but it may work for you)

    import pyvips
    
    
    # To install 'pyvips' refers to https://pypi.org/project/pyvips/
    #  1. Intall libvips shared library from https://jcupitt.github.io/libvips/install.html
    #  2. Set the PATH variable.
    #  3. run pip install pyvips
    
    def generate_tweet_image():
        cnum = 1
        output_file = "tweet_file.png"
        text = u''
        with open("hindi.txt", "r", encoding='UTF-8') as filestream:
            for l in filestream.readlines():
                text = text + f'{cnum}) {l}'
                cnum += 1
    
        MAX_W, MAX_H = 1500, 1500
    
        # See for API https://jcupitt.github.io/pyvips/vimage.html#pyvips.Image.text
    
        # font file: ARIALUNI.TTF
        image = pyvips.Image.text(text, width=MAX_W, height=MAX_H, font='Arial Unicode MS', dpi=96)
        image.write_to_file(output_file)
        print(f'File Written at : {output_file}')
    
    
    generate_tweet_image()
    

    Output:

    Hope this helps.

提交回复
热议问题