Created
May 18, 2012 09:23
-
-
Save syshack/2724229 to your computer and use it in GitHub Desktop.
text2png for sae demo
This file contains hidden or 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
| from bottle import * | |
| import sae.storage as sst | |
| from StringIO import StringIO | |
| import sae | |
| app = Bottle() | |
| debug(True) | |
| @app.get('/t2p') | |
| def text_form(): | |
| return ''' | |
| <form method="POST"> | |
| <textarea id="text" name ="text" rows="3" cols="20"> | |
| </textarea> | |
| <input type="submit" name="Submit" /> | |
| </form> | |
| ''' | |
| def text2png(text): | |
| # Configurations: | |
| adtexts = [u'by:syshack'] | |
| textcolor = "#000000" | |
| adcolor = "#FF0000" | |
| # Don't touch the code below | |
| from PIL import Image, ImageDraw, ImageFont | |
| import uuid | |
| # Build rich text for ads | |
| ad = [] | |
| for adtext in adtexts: | |
| ad += [(adtext.encode('gbk'), adcolor)] | |
| # Wrap line for text | |
| # Special treated Chinese characters | |
| # Workaround By Felix Yan - 20110508 | |
| wraptext = [""] | |
| l = 0 | |
| for i in text.decode('utf-8'): | |
| fi = i.encode('gbk') | |
| delta = len(fi) | |
| if i == '\n': | |
| wraptext += [""] | |
| l = 0 | |
| elif l + delta > 40: | |
| wraptext += [fi] | |
| l = delta | |
| else: | |
| wraptext[-1] += fi | |
| l += delta | |
| # Format wrapped lines to rich text | |
| wrap = [(text, textcolor) for text in wraptext] | |
| wrap += ad | |
| # Draw picture | |
| i = Image.new("RGB", (330, len(wrap) * 17 + 5), "#FFFFFF") | |
| d = ImageDraw.Draw(i) | |
| f = ImageFont.truetype('ch.ttf', 16) | |
| for num, (text, color) in enumerate(wrap): | |
| d.text((2, 17 * num + 1), text.decode('gbk'), font = f, fill = color) | |
| io=StringIO() | |
| i.save(io,"PNG") | |
| io.seek(0) | |
| iStr=io.read() | |
| s=sst.Client() | |
| # Write result to a temp file | |
| filename = uuid.uuid4().hex + ".png" | |
| ob=sst.Object(iStr,expires='A3600',content_type='image/x-png') | |
| #Don't use content_encoding='gzip' option | |
| s.put('png',filename,ob) | |
| url = s.url('png', filename) | |
| return url | |
| #---------------------------------------------------------------------- | |
| @app.post('/t2p') | |
| def t2p(): | |
| text = request.forms.get('text') | |
| link=text2png(text) | |
| img='<img src="'+link+'" />' | |
| return img | |
| application = sae.create_wsgi_app(app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment