import md5 from django.http import HttpResponse, HttpResponseNotModified, HttpResponseForbidden import Image, ImageFont, ImageDraw from django.conf import settings def text_to_image(request, fontalias, orientation, size=20): orientationmap = {'normal': 0, 'left': 90, 'right': 270} fontmap = { 'vera': "VeraSe.ttf", 'pixel': "Pixel.ttf", } try: orientation = orientationmap[orientation] except KeyError: return HttpResponseForbidden("unsupported orientation") try: fontfile = settings.MEDIA_ROOT + 'ttf/' + fontmap[fontalias] except KeyError: return HttpResponseForbidden("font alias not supported") if request.GET.has_key('text') and len(request.GET['text']): header = request.GET['text'] else: header = 'I fart in your general direction' if request.GET.has_key('size'): try: size = int(request.GET['size']) except: pass etag = md5.new(header + fontalias).hexdigest() if request.META.get("HTTP_IF_NONE_MATCH") == etag: return HttpResponseNotModified() palette = [ 0,0,0, #0 black 255,255,255 #1 white ] imf = ImageFont.truetype(fontfile, size) size = imf.getsize(header) im = Image.new("P", size, color=1) im.putpalette(palette) draw = ImageDraw.Draw(im) draw.text((0, 0), header, font=imf, fill=0) response = HttpResponse(mimetype="image/gif") im = im.rotate(orientation) im.save(response, "GIF", transparency=1) response["ETag"] = etag return response