PIL 图片处理 文字添加

PIL简介:

  python平台事实上的图片处理标准库,功能强大,API简单易用

PIL安装:

pip install PIL

直接绘图插入文字

#!/usr/bin/env python
from PIL import Image, ImageDraw, ImageFont, ImageFilter
# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
text = '你要插入的文字'
# 输出文字: for t in range(4):
  position =
(60 * t + 10, 10)
  draw.text(position, text, font=font, fill="#000000", spacing=0, align='left')
image.save(
'code.jpg', 'jpeg');

打开已有的图片插入文字

#!/usr/bin/env python
from PIL import Image, ImageDraw, ImageFont, ImageFilter

image = Image.open('cat.jpg')
# 创建Font对象:
font = ImageFont.truetype('Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
text = '你要插入的文字'
# 输出文字:
for t in range(4):
  position =(60 * t + 10, 10)
  draw.text(position, text, font=font, fill="#000000", spacing=0, align='left') 
image.save('code.jpg', 'jpeg');

封装成方法

def insert_text(text, fone_type_file, font_size, im, position):
    '''
    ** text 要插入的文字
    ** fone_type_file 文字类型文件名称
    ** font_size 文字大小
    ** im 背景图片
    ** position 要插入的位置
    '''

    datas = text.split('\n')
    data = ''
    if not datas:
        datas = [text]
    for d in datas:
        if not d:
            d = ' '
        elif len(d) > 31:
            d1 = d[:30] + '\n'
            d2 = d[30:]
            d = d1 + ' \n'+ d2
        data += (d +'\n')
        data += ' \n'

    data = data[:-1]
    dr = ImageDraw.Draw(im)
    font = ImageFont.truetype(fone_type_file, font_size)

    dr.text(position, data, font=font, fill="#000000", spacing=0, align='left')
    im.save("t.png")
    return im, len(datas)

 

posted @ 2018-06-19 10:58  city.king  阅读(3127)  评论(0编辑  收藏  举报