Elsayed Mohamed
Elsayed Mohamed

Reputation: 1

arabic text problem with pillow python after trying Arabic reshaper and bidi after spending hours

I tried using deepseek and my mind and spent hours not solving it

from PIL import Image, ImageDraw, ImageFont from arabic_reshaper import ArabicReshaper from bidi.algorithm import get_display
    
def create_proper_arabic_image(): 
    try: # 1. Configuration 
        text = "السلام عليكم" 
        font_path = "Amiri-1.001\Amiri-Regular.ttf" 
        output_path = "correct_arabic.png"
    
        # 2. Initialize processors
        reshaper = ArabicReshaper()
        img = Image.new("RGB", (800, 200), (255, 255, 255))
        draw = ImageDraw.Draw(img)
        
        # 3. Load and verify font
        font = ImageFont.truetype(font_path, 60)
        print(f"Font Supports Arabic: {any('arabic' in n.lower() for n in font.getname())}")
        
        # 4. Process text
        reshaped = reshaper.reshape(text)
        bidi_text = get_display(reshaped)
        print(f"Final Text: {bidi_text}")  # Verify RTL
        
        # 5. Calculate RTL position
        bbox = draw.textbbox((0, 0), bidi_text, font=font, direction='rtl', language='ar')
        x = img.width - (bbox[2] - bbox[0]) - 20  # Right-align
        y = 50
        
        # 6. Draw text
        draw.text((x, y), bidi_text, font=font, fill=(0,0,0), direction='rtl', language='ar')
        
        img.save(output_path)
        print(f"Successfully created: {output_path}")
        
    except Exception as e:
        print(f"Error: {str(e)}")

create_proper_arabic_image()

The best result I got:

Arabic text

I expected proper Arabic text on the image proper alignment.
enter image description herean image showing the proper arabic writing but the text still needs to be to the right

Upvotes: -4

Views: 53

Answers (0)

Related Questions