Created
October 11, 2012 13:19
-
-
Save 013231/3872222 to your computer and use it in GitHub Desktop.
Create a placeholder picture.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from tornado.web import Application, RequestHandler | |
from tornado.ioloop import IOLoop | |
from PIL import Image, ImageDraw, ImageFont, ImageColor | |
import cStringIO | |
import re | |
fontPath = '/Library/Fonts/Arial.ttf' | |
port = 8080 | |
def createImg(width, height, color, text, format): | |
img = Image.new('RGBA', (width, height), color) | |
draw = ImageDraw.Draw(img) | |
fontSize = 32 | |
while True: | |
font = ImageFont.truetype(fontPath, fontSize) | |
textWidth, textHeight = draw.textsize(text, font=font) | |
if textWidth > width or textHeight > height: | |
fontSize /= 2 | |
else: | |
break | |
textLeft = (width - textWidth) / 2 | |
textTop = (height - textHeight) / 2 | |
textColor = 'White' if sum(ImageColor.getrgb(color)) < 255 * 3 / 2 else 'Black' | |
draw.text((textLeft, textTop), text, font=font, fill=textColor) | |
fim = cStringIO.StringIO() | |
img.save(fim, format) | |
binData = fim.getvalue() | |
fim.close() | |
return binData | |
class IndexHandler(RequestHandler): | |
def get(self): | |
sizeArg = self.get_argument('size', '512x512') | |
sizeMatch = re.match(r'(\d+)[xX](\d+)', sizeArg) | |
width = int(sizeMatch.group(1)) | |
height = int(sizeMatch.group(2)) | |
color = self.get_argument('color', 'gray') | |
try: | |
int(color, 16) | |
color = '#' + color | |
except ValueError: | |
pass | |
text = self.get_argument('text', '%s * %s' % (width, height)) | |
img = createImg(width, height, color, text, 'PNG') | |
self.set_header('content-type', 'image/png') | |
self.set_header('content-length', len(img)) | |
self.write(img) | |
appSettings = { | |
'debug': True, | |
} | |
application = Application([ | |
('/', IndexHandler), | |
], **appSettings) | |
if __name__ == '__main__': | |
application.listen(port) | |
IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment