# $Id$ # simple PIL ImageDraw text wrapper, based on WCK sample code from # http://effbot.org/zone/wck-5.htm import Image, ImageDraw, ImageFont TEXT = """ I tell you I have been in the editorial business going on fourteen years, and it is the first time I ever heard of a man's having to know anything in order to edit a newspaper. You turnip! """ def drawtext(draw, text, font, color, bbox): x0, y0, x1, y1 = bbox # note: y1 is ignored space = draw.textsize(" ", font)[0] words = text.split() x = x0; y = y0; h = 0 for word in words: # check size of this word w, h = draw.textsize(word, font) # figure out where to draw it if x > x0: x += space if x + w > x1: # new line x = x0 y += h draw.text((x, y), word, font=font, fill=color) x += w return y + h # -------------------------------------------------------------------- if __name__ == "__main__": def test(): im = Image.new("RGB", (500, 500), "white") draw = ImageDraw.Draw(im) font = ImageFont.truetype("arial.ttf", 20) bbox = (100, 100, 400, 400) draw.rectangle(bbox, outline="red") drawtext(draw, TEXT, font, "black", bbox) im.show() test()