It's designed to work with the built-in Django template system by providing a simple template filter you can use to render images dynamically.
The first showcase is Talent Nord. I hope to get a longer list as more people start using it. The design of Talent Nord is by Fata Morgana, house of two intelligent designers.
I think you need a pretty recent Django for the app to work. Here's the code that does the hard work:
import md5, os
import Image, ImageFont, ImageDraw, ImageColor
from django.conf import settings
def render(text, fontalias, size = 12, color = "#000", rotation = 0):
"""Construct image from text.
Returns a tuple with the image file path, width and height. Takes
the parameters 'fontalias', 'size' (default 12), 'color' (default
black) as CSS hex string, and 'rotation' (default 0) which is the
degrees to rotate the text counter-clockwise. The constructed
image is stored in a cache under the media root in the
RENDERTEXT_DIR set in settings.py (default is 'rendertext/').
The font file to use is determined by mapping the fontalias
through the RENDERTEXT_FONTMAP setting, a dictionary from
fontalias strings to font file paths, e.g. {'verdana':
'/home/django/fonts/verdana.ttf'}."""
# get settings
render_dir = "rendertext/"
if hasattr(settings, "RENDERTEXT_DIR"):
render_dir = settings.RENDERTEXT_DIR
fontmap = settings.RENDERTEXT_FONTMAP
fontfile = fontmap[fontalias]
info = "|".join([text, fontalias, str(size), str(color), str(rotation)])
name = md5.new(info.encode('utf-8')).hexdigest()
filepath = render_dir + name + ".png"
dim = (-1, -1)
if not os.access(settings.MEDIA_ROOT + filepath, os.F_OK):
# construct the image
imf = ImageFont.truetype(fontfile, size)
dim = imf.getsize(text)
im = Image.new("RGBA", dim, ImageColor.getrgb(color) + (0,))
draw = ImageDraw.Draw(im)
weird_font_renderer_fix = " "
draw.text((0, 0), text + weird_font_renderer_fix, font=imf, fill=color)
if rotation != 0:
im = im.rotate(rotation, Image.BICUBIC, True)
dim = im.size
if not os.access(settings.MEDIA_ROOT + render_dir, os.F_OK):
os.makedirs(settings.MEDIA_ROOT + render_dir)
im.save(settings.MEDIA_ROOT + filepath, "PNG")
else:
# read width and height
im = Image.open(settings.MEDIA_ROOT + filepath)
dim = im.size
return (settings.MEDIA_URL + filepath, dim[0], dim[1])
def render_tag(text, *args, **kwargs):
"""Construct image tag from text."""
(path, width, height) = render(text, *args, **kwargs)
if not path:
return ""
else:
dim = ""
if width > 0 and height > 0:
dim = 'width="%s" height="%s" ' % (width, height)
return '<img src="%s" alt="%s" %s/>' % (path, text, dim)
No comments:
Post a Comment