2025年6月4日 星期三 乙巳(蛇)年 三月初八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python: 纯文本转PNG

时间:11-13来源:作者:点击数:43

Python: 纯文本转PNG

  • 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

效果图:

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门