#-*- coding:utf-8 -*-
import Image, ImageDraw, ImageFont, uuid
def text2png(text):
# config:
adTexts = ['---------------', 'http://www.planabc.net']
imgBg = '#FFFFFF'
textColor = "#000000"
adColor = "#FF0000"
ttf = "C:\Windows\Fonts\STXIHEI.TTF"
fontSize = 20
tmp = 'tmp/'
# Build rich text for ads
ads = []
for adText in adTexts:
ads += [(adText.decode('utf-8'), adColor)]
# Format wrapped lines to rich text
bodyTexts = [""]
l = 0
# x.decode() ==> unicode
for character in text.decode('utf-8'):
c = character
delta = len(c)
if c == '\n':
bodyTexts += [""]
l = 0
elif l + delta > 40:
bodyTexts += [c]
l = delta
else:
bodyTexts[-1] += c
l += delta
body = [(text, textColor) for text in bodyTexts]
body += ads
# Draw picture
img = Image.new("RGB", (330, len(body) * fontSize + 5), imgBg)
# Ref: [blog.163.com] draw = ImageDraw.Draw(img)
font = ImageFont.truetype(ttf, fontSize)
for num, (text, color) in enumerate(body):
draw.text((2, fontSize * num), text, font=font, fill=color)
# Write result to a temp file
filename = uuid.uuid4().hex + ".png"
file = open(tmp + filename, "wb")
img.save(file, "PNG")
return tmp + filename
if __name__ == '__main__':
text2png( "怿飞")
参考自:http://simple-is-better.com/news/detail-289