Login

simple text image view

Author:
derelm
Posted:
March 19, 2007
Language:
Python
Version:
Pre .96
Tags:
text image text-image-view
Score:
2 (after 2 ratings)

Credit goes to

Andrew Gwozdziewycz and Jacob Kaplan-Moss

This is basically their code. Only differences:

  • orientation can be customized
  • size can be customized
  • GIF-Image with transparency is created

Note: Because of the minimum palette that's used, the font isn't antialiased/smoothened.

My url for this view looks like so:

(r'^img/(?P<fontalias>\w+)/(?P<orientation>(normal|left|right))/$',
            'view.text_to_image')
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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

More like this

  1. load m2m fields objects by dirol 4 years, 10 months ago
  2. Tags & filters for rendering search results by exogen 7 years ago
  3. Date/time util template filters by marinho 7 years, 5 months ago
  4. Git recent commits template tag by david 6 years, 8 months ago
  5. Template filter that divides a list into exact columns by davmuz 3 years, 2 months ago

Comments

Please login first before commenting.