Created
May 7, 2012 01:27
-
-
Save syshack/2625322 to your computer and use it in GitHub Desktop.
text2png
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
| #/bin/env python | |
| #-*- coding:utf-8 -*- | |
| from bottle import * | |
| @get('/t2p') | |
| def text_form(): | |
| return ''' | |
| <form method="POST"> | |
| <input type="text" name="text" /> | |
| <input type="submit" name="Submit" /> | |
| </form> | |
| ''' | |
| def text2png(text): | |
| # Configurations: | |
| adtexts = [u'by:syshack'] | |
| textcolor = "#000000" | |
| adcolor = "#FF0000" | |
| import Image, ImageDraw, ImageFont, 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) | |
| # Write result to a temp file | |
| filename = uuid.uuid4().hex + ".png" | |
| with open("png/" + filename, "wb") as s: | |
| i.save(s, "PNG") | |
| link="png/" + filename | |
| return link | |
| #---------------------------------------------------------------------- | |
| @post('/t2p') | |
| def t2p(): | |
| text = request.forms.get('text') | |
| link=text2png(text) | |
| return link | |
| run(host = '0.0.0.0', port = 8080) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment