simple text image view

 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. Date/time util template filters by marinho 5 years, 7 months ago
  2. Tags & filters for rendering search results by exogen 5 years, 2 months ago
  3. NewForms Readonly / Edit Pattern by FreddieP 5 years, 6 months ago
  4. Add rel=lightbox to all image-links by bartTC 5 years, 5 months ago
  5. CSS Preprocessor by jokull 5 years, 8 months ago

Comments

akaihola (on March 3, 2009):

django-rendertext is based on this snippet.

#

akaihola (on March 3, 2009):

Alternative implementations:

#

akaihola (on March 6, 2009):

django-cairo-text is a re-usable app based on code from Andrew Godwin's blog post.

#

DudleyJackie (on December 31, 2011):

I think that to get the loans from banks you ought to present a great reason. But, one time I've got a sba loan, because I wanted to buy a house.

#

(Forgotten your password?)