Skip to content

Instantly share code, notes, and snippets.

@erfanhs
Last active March 9, 2021 09:50
Show Gist options
  • Save erfanhs/de778da742139ab8c832a3e2e5925a00 to your computer and use it in GitHub Desktop.
Save erfanhs/de778da742139ab8c832a3e2e5925a00 to your computer and use it in GitHub Desktop.
write persian text on image (python+pillow)
import arabic_reshaper # pip install arabic-reshaper
from bidi.algorithm import get_display # pip install python-bidi
from PIL import ImageFont, Image, ImageDraw # pip install Pillow
def wrap(text, maxLen):
res_lines = []
for line in text.split('\n'):
lines = []
words = line.split(' ')
line = ''
for word in words:
if len(line+word) >= maxLen:
lines.append(line.strip())
line = ''
line += word + ' '
continue
else:
line += word + ' '
if line:
lines.append(line.strip())
line = ''
res_lines += lines
return '\n'.join(res_lines)
def write_on_image(text, img, font, font_size, position, rgb, aling, text_max_width=100, spacing=20, out='out.jpg', save=True):
text = wrap(text, text_max_width) # wrap text
font = ImageFont.truetype(font, font_size) # load font file
image = Image.open(img) # open image
reshaped_text = arabic_reshaper.reshape(text)
bidi_text = get_display(reshaped_text)
draw = ImageDraw.Draw(image)
width, height = image.size # image size (px)
w, h = draw.textsize(text, font=font) # text size (px)
draw.text(position, bidi_text, rgb, font=font, align=align, spacing=spacing) # write text
if save:
image.save(out)
return image
if __name__ == '__main__':
image = write_on_image('سلام چه خبر؟', 'in.jpg', './iransans.ttf', 50, (100,200), (0,0,0), 'center')
image.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment