python将文本转换成图片输出的方法

yipeiwu_com6年前Python基础

本文实例讲述了python将文本转换成图片输出的方法。分享给大家供大家参考。具体实现方法如下:

#-*- coding:utf-8 -*-
from PIL import Image,ImageFont,ImageDraw
text = u'欢迎访问【听图阁-专注于Python设计】,//www.jb51.net'
font = ImageFont.truetype("msyh.ttf",18)
lines = []
line =''
for word in text.split():
  print word
  if font.getsize(line+word)[0] >= 300:
    lines.append(line)
    line = u''
    line += word 
    print 'size=',font.getsize(line+word)[0]
  else:
    line = line + word
line_height = font.getsize(text)[1]
img_height = line_height*(len(lines)+1)
print 'len=',len(lines)
print 'lines=',lines
im = Image.new("RGB",(444,img_height),(255,255,255))
dr = ImageDraw.Draw(im)
x,y=5,5
for line in lines:
  dr.text((x,y),line,font=font,fill="#000000")
  y += line_height
im.save("1.1.jpg")

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python基于scapy实现修改IP发送请求的方法示例

本文实例讲述了Python基于scapy实现修改IP发送请求的方法。分享给大家供大家参考,具体如下: 今天同事想测试WAF的页面统计功能,所以需要模拟多个IP向多个域名发送请求,也就是需...

详解pyinstaller selenium python3 chrome打包问题

详解pyinstaller selenium python3 chrome打包问题

今天打包selenium一个简单的请求,打完包本机运行exe没有问题,换台机器就闪退,非常蛋疼找了半天原因。 下面简述下,防止踩坑,如果闪退十有八九是浏览器版本跟浏览器插件对不上。 首先...

Python中整数的缓存机制讲解

在python中,如下代码结果一定不会让你吃惊: Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1...

python 类之间的参数传递方式

练手记录以及调试步骤. class A(object): def __init__(self,a="A"): print("enter",a) print("le...

详解Python3序列赋值、序列解包

上节我们提到解决赋值中等号两边参数不一致的方法可以通过切片,但在Python3中我们可以利用特定的语法更加方便的处理这种情况,如下示例。 当带 * 出现在结尾间时 L = [1, 2...