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
pass
else:
font_size = FontSize
fnt = ImageFont.truetype(font_dir+font, font_size)
w, h= fnt.getsize(text)
img = Image.new('RGBA', (w, h), bg)
draw = ImageDraw.Draw(img)
draw.fontmode = "0"
draw.text((0,0), text, font=fnt, fill=fg)
img.save(font_dir+img_name,"JPEG",quality=100)
imgtag = '<img src="'+settings.MEDIA_URL+'txt2img/'+img_name+'" alt="'+text+'" />'
return imgtag
register.simple_tag(txt2img)
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.
Comments
Ole Laursen commented, on November 23, 2007 at 6:42 p.m.:
Hi!
I believe there's a couple of snippets on http://djangosnippets.org, and I released a library for this a month or two ago:
http://code.google.com/p/django-rende...
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.
Post a comment