Generating Dynamic Text Images

Taken from Jacobian.org http://www.jacobian.org/2006/jun/30/improved-text-image-view/

import md5
from django.conf import settings
from django.http import (HttpResponse,
                         HttpResponseNotModified,
                         HTTPResponseForbidden)
import Image, ImageFont, ImageDraw

def view_header(request, fontalias):
    try:
        fontfile = settings.DYNAMIC_FONT_ALIASES[fontalias]
    except:
        return HttpResponseForbidden("font alias not supported")

    header = request.GET.get('text', 'Hello world')

    etag = md5.new(header + fontalias).hexdigest()
    if request.META.get("HTTP_IF_NONE_MATCH") == etag:
        return HttpResponseNotModified()

    imf = ImageFont.truetype(fontfile, 20)
    size = imf.getsize(header)
    im = Image.new("RGB", size)
    draw = ImageDraw.Draw(im)
    draw.text((0, 0), header, font=imf)

    response = HTTPResponse(mimetype="image/png")
    im.save(response, "PNG")
    response["e-tag"] = etag
    return response
Last modified 15 years ago Last modified on Dec 23, 2009, 1:42:21 AM
Note: See TracWiki for help on using the wiki.
Back to Top