Python: 纯文本转 PNG

这个方法效果一般般, 只是”可用”的程度, 近似于长微博(changweibo.com)的效果…

字体方面, 我选用了YaHeiYt等宽字体(来源: http://yutuo5.blog.163.com/blog/static/300846782010019113537523/), 效果一般, 具体见下图:

 

def text2png(text):
    # Configurations:
    adtexts = [u'---------------', u'广告太多是不对的!']
    textcolor = "#000000"
    adcolor = "#FF0000"

    # Don't touch the code below
    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("YaHeiYt.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("/tmp/" + filename, "wb") as s:
        i.save(s, "PNG")
    return "/tmp/" + filename

 

感谢 freetstar 推荐,关于 freetstar

Twitter:http://twitter.com/freetstar
博客:http://www.freetstar.com/
关注和奉献Tianjin Linux User Group的建设,关注开源社区,Linux爱好者,python初学者,希望成为一名geek,爱好交流

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。