首页 > 其他 > 详细

PIL 图片处理 文字添加

时间:2018-06-19 11:09:49      阅读:183      评论:0      收藏:0      [点我收藏+]

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)

图片转pdf

from PIL import Image

im = Image.open(cat.jpg)
im2.save(cat2.pdf, pdf)

直接把图片保存为pdf是图片的模式一定要为RGB模式,否则就要转换为RGB模式,转换方法为im.convert(mode) 

PIL 图片处理 文字添加

原文:https://www.cnblogs.com/cityking/p/9197596.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!