python add persian text to image

172 views
Skip to first unread message

vahid chakoshy

unread,
Dec 25, 2012, 11:23:50 AM12/25/12
to persian-...@googlegroups.com
hi, how can i add persian text to image with python?

Saeed Rasooli

unread,
Dec 25, 2012, 3:58:30 PM12/25/12
to vahid chakoshy, persian-...@googlegroups.com
Since PIL (Python Imaging Library) does not support BIDI, you need an extra (third-party) library with BIDI support, like Cairo which is underlying library of GTK+, or choose Qt (base of KDE).
Cairo's binding is part of PyGTK

On Tue, Dec 25, 2012 at 7:53 PM, vahid chakoshy <vcha...@gmail.com> wrote:
hi, how can i add persian text to image with python?

Saeed Rasooli

unread,
Dec 25, 2012, 4:49:40 PM12/25/12
to vahid chakoshy, persian-...@googlegroups.com
Unfortunately, the whole gtk/cairo/pango thing and the relation between them is a little complicated, but I wrote a sample code to draw a persian text over a new image file (with one line change, you can put it on an existing image file)
__________________________
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

import gtk
from gtk import gdk

import pango

pixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, False, 8, 300, 200)
#pixbuf = gtk.gdk.pixbuf_new_from_file("image.png")

pixmap, mask = pixbuf.render_pixmap_and_mask()
#pixmap.draw_rectangle(pixmap.new_gc(), True, x, y, w, h)
cr = gdk.pango_context_get()
text_layout = pango.Layout(cr)
text_layout.set_text(u'امتحان')
text_layout.set_font_description(pango.FontDescription('Sans Bold 40'))
pixmap.draw_layout(pixmap.new_gc(), 50, 50, text_layout, foreground=gdk.Color('white'))


pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, 300, 200)
pixbuf.save('fa.png', 'png')

Behdad Esfahbod

unread,
Dec 27, 2012, 4:40:33 PM12/27/12
to Saeed Rasooli, vahid chakoshy, persian-...@googlegroups.com
You don't really need gdk except for loading/saving non-PNG formats. Here's
minimal pypangocairo code for example:

http://marc.info/?l=cairo&m=121692252128947

behdad
--
behdad
http://behdad.org/

Saeed Rasooli

unread,
Dec 27, 2012, 5:32:31 PM12/27/12
to Behdad Esfahbod, vahid chakoshy, persian-...@googlegroups.com
Thanks Behdad, I almost forgot about ImageSurface
I personally prefer the pangocairo one because pango Layout is much more flexible, for example we can analyze the text layout (to adjust font size and position...) before we draw it.
Reply all
Reply to author
Forward
0 new messages