Rendering text as an image using a django template tag

This templatetag allows you to use pil (python image library) to render out text in a custom font and colour. I recently created this template tag for a project I am working on, I haven't seen anything similar so I thought I would share it.

Here is the code for the templatetag:

    from django.conf import settings
    from django.template import Library, Node

    import Image, ImageDraw, ImageFont
    from os import chdir, path

    register = Library()

    def txt2img(text,bg="#ffffff",fg="#000000",font="GOTHIC.TTF",FontSize=14):
        font_dir = settings.MEDIA_ROOT+"/txt2img/"   # Set the directory to store the images
        img_name = text+"-"+bg.strip("#")+"-"+fg.strip("#")+".jpg" # Remove hashes
        if path.exists(font_dir+img_name): # Make sure img doesn't exist already
            font_size = FontSize
            fnt = ImageFont.truetype(font_dir+font, font_size)
            w, h= fnt.getsize(text)
            img ='RGBA', (w, h), bg)
            draw = ImageDraw.Draw(img)
            draw.fontmode = "0" 
            draw.text((0,0), text, font=fnt, fill=fg)
        imgtag = '<img src="'+settings.MEDIA_URL+'txt2img/'+img_name+'" alt="'+text+'" />'
        return imgtag


Now you need to create the "txt2img" folder in your media folder and in it place the font or fonts you intend to use.

Now in your template, load the templatetag:

    {% load txt2img %}

You may now call the tag like so:

    {% txt2img "Some Text" "#faf9f4" "#f1a096" "TrajanPro-Regular.otf" 22 %}

Thats text,background colour, foreground colour, font name and font size. Text can be a "string" or a template variable (page.title). The plugin will create the image once only if it finds it wasn't already created.

Posted on November 21, 2007
Tags: Django, Python



Ole Laursen commented, on November 23, 2007 at 6:42 p.m.:


I believe there's a couple of snippets on, and I released a library for this a month or two ago:

It's basically the same as you're doing. Note that you'll get crisper and probably also smaller files from using PNG or GIF instead of JPEG.


Adam commented, on November 24, 2007 at 3:12 p.m.:

Wow, thats a lot more complete than mine, thanks for the heads up.


Eric commented, on December 28, 2008 at 3:31 a.m.:

Can yoyu tell me, where do you put the code? Do I put it in the file? If I have to put it in its own file, where does that file go? In the project or the site folder?

Thank you very much.


home loans commented, on August 30, 2011 at 1:18 a.m.:

I received 1 st mortgage loans when I was 25 and it aided me a lot. But, I require the credit loan over again.

Post a comment

Your name: