| | 1 | |
| | 2 | == Generating Dynamic Text Images== |
| | 3 | |
| | 4 | Taken from Jacobian.org |
| | 5 | [http://www.jacobian.org/2006/jun/30/improved-text-image-view/] |
| | 6 | |
| | 7 | |
| | 8 | |
| | 9 | {{{ |
| | 10 | import md5 |
| | 11 | from django.conf import settings |
| | 12 | from django.http import (HttpResponse, |
| | 13 | HttpResponseNotModified, |
| | 14 | HTTPResponseForbidden) |
| | 15 | import Image, ImageFont, ImageDraw |
| | 16 | |
| | 17 | def view_header(request, fontalias): |
| | 18 | try: |
| | 19 | fontfile = settings.DYNAMIC_FONT_ALIASES[fontalias] |
| | 20 | except: |
| | 21 | return HttpResponseForbidden("font alias not supported") |
| | 22 | |
| | 23 | if request.GET.has_key('text'): |
| | 24 | header = request.GET['text'] |
| | 25 | else: |
| | 26 | header = 'Hello world' |
| | 27 | |
| | 28 | etag = md5.new(header).hexdigest() |
| | 29 | if request.META.get("HTTP_IF_NONE_MATCH") == etag: |
| | 30 | return HttpResponseNotModified() |
| | 31 | |
| | 32 | imf = ImageFont.truetype(fontfile, 20) |
| | 33 | size = imf.getsize(header) |
| | 34 | im = Image.new("RGB", size) |
| | 35 | draw = ImageDraw.Draw(im) |
| | 36 | draw.text((0, 0), header, font=imf) |
| | 37 | |
| | 38 | response = HTTPResponse(mimetype="image/png") |
| | 39 | im.save(response, "PNG") |
| | 40 | response["e-tag"] = etag |
| | 41 | return response |
| | 42 | |
| | 43 | }}} |