#!/usr/bin/python2.4 import cairo, sys def text_to_image(text, font, size=72): text = text[:100] size = min(100, size) surface = cairo.ImageSurface(cairo.FORMAT_A1, 1, 1) ctx = cairo.Context(surface) ctx.select_font_face(font) ctx.set_font_size(size) x_bearing, y_bearing, twidth, theight = ctx.text_extents(text)[:4] descent = ctx.font_extents()[1] del surface del ctx width = min(int(twidth+x_bearing+8), 1200) height = min(int(theight+descent+8), 200) surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height) ctx = cairo.Context(surface) # First, clear the surface to white ctx.set_source_rgba(1, 1, 1, 1) ctx.rectangle(0, 0, width, height) ctx.fill() # Put a fine grey line around the outside ctx.set_source_rgba(0, 0, 0, .25) ctx.rectangle(0, 0, width, height) ctx.stroke() # Set the font ctx.select_font_face(font) ctx.set_font_size(size) # And draw the desired letters ctx.set_source_rgb(0, 0, 0) ctx.move_to(-x_bearing+4, theight+4) ctx.show_text(text) return surface def main(): import cgi, cgitb; cgitb.enable() f = cgi.FieldStorage() if f.has_key('text') and f.has_key('font'): try: size = int(f['size'].value) except StandardError: size = 72 text = f['text'].value font = f['font'].value surface = text_to_image(text, font, size) sys.stdout.write("Content-Type: image/png\r\n\r\n") surface.write_to_png(sys.stdout) else: fonts = ['Sans', 'Serif', 'Courier'] fonts = "".join("" % (cgi.escape(i)) for i in fonts) sizes = "".join("" % i for i in range(12, 101, 4)) sys.stdout.write("Content-Type: text/html\r\n\r\n") sys.stdout.write(""" Python/Cairo Text to Image demo
""" % (fonts, sizes)) main()