Skip to content

Instantly share code, notes, and snippets.

@atorkhov
Created April 17, 2013 11:31
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atorkhov/5403562 to your computer and use it in GitHub Desktop.
Save atorkhov/5403562 to your computer and use it in GitHub Desktop.
PIL word wrap
# http://tanner-tech.googlecode.com/svn-history/r197/trunk/NewWorldMap/cardgen/eniCards.py
import Image, ImageDraw, ImageFont
# load an existing image
photo = Image.open("lyn.jpg")
photoSize = photo.size
# create a new, empty image
card = Image.new('RGB', (600, 600), color=(255,255,255))
# paste photo at some point
card.paste(photo, (30,30))
# draw lines around the photo
draw = ImageDraw.Draw(card)
draw.line((25,25, photoSize[0]+35, 25), fill=(255,0,0), width=2)
draw.line((25,photoSize[1]+35, photoSize[0]+35, photoSize[1]+35), fill=(255,0,0), width=2)
# This function comes from the web:
# http://jesselegg.com/archives/2009/09/5/simple-word-wrap-algorithm-pythons-pil/
def draw_word_wrap(draw, text,
xpos=0, ypos=0,
max_width=130,
fill=(250,0,0),
font=ImageFont.truetype("arial.ttf", 50)):
'''Draw the given ``text`` to the x and y position of the image, using
the minimum length word-wrapping algorithm to restrict the text to
a pixel width of ``max_width.``
'''
text_size_x, text_size_y = draw.textsize(text, font=font)
remaining = max_width
space_width, space_height = draw.textsize(' ', font=font)
# use this list as a stack, push/popping each line
output_text = []
# split on whitespace...
for word in text.split(None):
word_width, word_height = draw.textsize(word, font=font)
if word_width + space_width > remaining:
output_text.append(word)
remaining = max_width - word_width
else:
if not output_text:
output_text.append(word)
else:
output = output_text.pop()
output += ' %s' % word
output_text.append(output)
remaining = remaining - (word_width + space_width)
for text in output_text:
draw.text((xpos, ypos), text, font=font, fill=fill)
ypos += text_size_y
# draw text
draw_word_wrap(draw,
"This is the title of my presentation. What happens after this?",
30+photoSize[0]+30,
30,
200)
text = '''Let's have some more text here that will be about the abstract, \
I am sure that this can go as long as I want it to be. More, more, more...'''
draw_word_wrap(draw, text,
30, 30+photoSize[1]+30,
max_width = 250,
fill=(0,0,255),
font= ImageFont.truetype("arial.ttf", 20))
card.show()
card.save('card.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment