from django.conf import settings from django.template import Library import Image, ImageDraw, ImageFont from os import path import hashlib register = Library() @register.filter def txt2img(text,FontSize=14,bg="#ffffff",fg="#000000",font="FreeMono.ttf"): ''' txt2img tag shows on the web text as images, helping to avoid get indexed email address and some other information you don't want to be on search engines. Fonts should reside in the same folder of txt2img. Usage: {{worker.email|txt2img:18|safe}} ''' font_dir = settings.MEDIA_ROOT+"/txt2img/" # Set the directory to store the images img_name_temp = text+"-"+bg.strip("#")+"-"+fg.strip("#")+"-"+str(FontSize) # Remove hashes img_name="%s.jpg" % (hashlib.md5(img_name_temp).hexdigest()) 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 = ''+text+'' return imgtag