Is there any way to write Arabic text on images in python

Viewed 587

I used to see many programs that can render arabic text with no bugs just fine, but when it comes to python there is only one lib that i know of (arabic_reshaper) and it's not efficient yet as it contains bugs, so i wonder if there any way around like an api or some twisted efficient way to do this task?

2 Answers

Yes. You'll have to use arabic_reshaper & python-bidi and a proper font. After trying many fonts I found only 2 fonts working: "Pak Nastaleeq.ttf" & "AA Sameer Qamri Regular.ttf" You can download the .ttf file of any of these fonts & use that. Here's a n example code in python depicting how to do this:

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import arabic_reshaper
from bidi.algorithm import get_display
text = "چوكسے ہنجاریں الجمل تیج اکساہٹ"
reshaped_p = arabic_reshaper.reshape(text)
text = get_display(reshaped_p)
cat_image = Image.open("test_image.png")
drawing_on_img = ImageDraw.Draw(cat_image)
font = ImageFont.truetype('Pak Nastaleeq.ttf',size=15)
text_color = (201,50,250)
text_coordinates = (0,0)
drawing_on_img.text(text_coordinates,text,font=font,fill='black')
cat_image.save("text_on_test_imager.png")

You can use Pillow without arabic_reshaper.

First of all you need have libraqm on your path. The Raqm library encapsulates the logic for complex text layouts and provides a convenient API. libraqm relies on the following libraries: FreeType, HarfBuzz, FriBiDi, make sure that you install them before installing libraqm if not available as package in your system.

if you using macos you can install libraqm with homebrew

brew install libraqm

Pillow wheels since version 8.2.0 include a modified version of libraqm that loads libfribidi at runtime if it is installed. The .text function takes the direction argument to the libraqm library, which enables pillow to support bidirectional text (using FriBiDi), shaping (using HarfBuzz), and also proper script itemization.

Additionally, you need a font for the language you wish to write in, such as an Arabic font.

import os

from PIL import Image, ImageDraw, ImageFont


def main():
    image = Image.open(os.path.join(os.path.dirname(__file__), "nature.jpeg"))
    font = ImageFont.truetype(
        os.path.join(
            os.path.dirname(__file__), "vazir-font-v28.0.0", "Vazir-Regular.ttf"
        ),
        100,
    )
    text = "طبیعت زیبای دوست داشتنی"
    canvas = ImageDraw.Draw(image)
    canvas.text((0, 0), text, (255, 255, 255), font=font, direction="rtl")
    image.save(os.path.join(os.path.dirname(__file__), "result.jpg"))

if __name__ == '__main__':
    main()
Related