Python:文字转图片

这是一个未完成的项目

涉及到一些复杂的问题,可以实现简单的文字转图片,但是换行控制的不是很好.后期有时间慢慢优化吧.在这里只是抱着研究技术的态度去的.

python Logo
image-2354

源代码

先上代码看一下,代码很简单,就不过多解释了.

需要使用Python3+.


#!/usr/bin/env python3
#-*- coding:utf-8 -*-
from PIL import Image,ImageFont,ImageDraw
import datetime

'''
使用Python生成长文字的图片.

2015.9.1 -- 基本功能已实现.
暂时还无法对文本内容很好组织

'''

_author_='prd'

class TextToImage(object):
def toImage(self,text):
text=text.replace('\n','\n ')
divj=30
text = text.replace('\u3000','')
#设置每一行有多少个字符
#定义展示图片的字体及字体大小
font = ImageFont.truetype("msyh.ttf",14)
#获取整个字符的长度
lens = len(text)/divj
#进行组装字符
lines=[text[x*divj:((x+1)*divj)] for x in range(0,(int(lens)+1 if isinstance(lens,float) else lens))]
print(lines)

#设置每一行的高度
line_height = font.getsize(text)[1]+20
#设置图片高度
img_height = line_height*(len(lines)+1)+50
#设置图片宽度
img_width=500
#定义新图片
im = Image.new("RGB",(img_width,img_height),'#EED5B7')
dr = ImageDraw.Draw(im)

#在图片上画文字
x,y=30,30
for li in lines:
dr.multiline_text(xy=(x,y),text=li,font=font,fill="#000000",spacing=2)
y += line_height

#定义底部所用字体
bottomfont = ImageFont.truetype("msyh.ttf",12)
#定义底部线的高度
bottomLineHeight=img_height-30
#在底部版权上面画一条线.
dr.line([0,bottomLineHeight,img_width,bottomLineHeight],'#ff0000',1)
#版权信息
dr.text((10,bottomLineHeight+5),'由Python3工具生成',font=bottomfont,fill="#ff0000")
#保存图片
fileName=str(datetime.datetime.now().microsecond)
im.save("%s.jpg" % (fileName))
print('文件保存成功,文件名是:%s.jpg' % (fileName))

if __name__ == '__main__':
to=TextToImage()
to.toImage("""
(The MIT License)

Copyright (c) 2012

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""")

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据