Login

simple text image view

Author:
derelm
Posted:
March 19, 2007
Language:
Python
Version:
Pre .96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.