Generating Complex Text Image with Pillow: The Challenges and the Solution

Introduction to Pillow

When working with image generation in Python, the Pillow library is a popular go-to tool. it’s flexible, fast, and was to use for manipulating images, drawing shapes and even rendering text. However, Pillow falls short when it comes to rendering complex scripts/texts such as Tibetan, Hindi, Urdu, Arabic, and other language with intricate rules for ligatures, contextual forms, and character reordering.

Why Pillow Struggles with Complex Scripts?

Pillow uses the FreeType library to render text onto images. While FreeType is excellent at rendering individual glyphs, however it doesn’t handle text layout which is crucial step for many complex scripts. This is where Libraqm comes in.

So What is Libraqm?

To put it simple Libraqm is an open-source library that provides complex text layout support. it acts as a bridge between multiple power text-processing libraries such as

  • HarfBuzz for text shaping (contextual forms).
  • FriBidi for bidirectional text handling
  • FreeType for rendering the shaped text.

Libraqm takes care of converting plain text and fonts into a properly shaped and positioned sequence of glyphs ready for rendering.

Installation guide are included in the following GitHub link

Libraqm GitHub Link: https://github.com/HOST-Oman/libraqm.

   pip uninstall Pillow  

        and then

   pip install --upgrade Pillow  --global-option="build_ext" --global-option="--enable-raqm"

DockerFile Setup.

When building docker image make sure to add the following command in your DockerFile

RUN apt-get update && apt-get install -y \ 
  libfreetype6-dev \
  libjpeg-dev \
  zlib1g-dev \
  libraqm-dev \
  fontconfig \
  && rm -rf /var/lib/apt/lists/*

Now your text should be rendered correctly after following all the above steps.

Conclusion.

Rendering complex scripts like Tibetan, Hindi, and Urdu is no small feat. These languages require a text rendering system that understands linguistic rules, visual shaping, and script directionality. While Pillow alone isn’t enough, combining it with libraqm transforms it into a powerful tool capable of producing high-quality multilingual text.

Related links:

2 Likes