1.导入PIL 包并导入相关的模块呢python
from PIL import Image, ImageFont, ImageDraw
遇到问题:由于使用的是python3 直接导入PIL的安装PIL模块的时候报错,使用pip install PIL 安装PIL报错:
Collecting PIL Could not find a version that satisfies the requirement PIL (from versions: ) No matching distribution found for PIL
缘由:PIL只支持python2.x ,全部使用python3 时候报错
解决方法:PIL 已经有一个分支项目,安装分支项目pillow一样支持PIL模块字体
pip install Pillow
2.PIL使用ui
1>导入须要修改的图片 ``` image = Image.open('./images/icon.png') ``` 2>设置字体的字体和大小 ``` # font = ImageFont.truetype(字体, 字体大小) font = ImageFont.truetype('arial.ttf', 20) ```
3.调用ImageDraw.Draw() 方法处理图片code
``` # 调用Draw方法,传入导入图片对象 draw = ImageDraw.Draw(image) draw.text((65, 0), '5', fill=(255, 10, 10), font=font) # draw.text方法是用来在图片上加上文字 # draw.text((x, y), '5', fill=(255, 10, 10), font=font) # (x,y)是一个元组用来表示生成的位置,x表x轴的位置,y表示在y轴的位置 # 须要注意的是:坐标轴的原点是图片的左上角 # '5' 表示的是须要在图片上写入的文字 # fill=(255, 10, 10) 表示的是RGB的色值 # font=font 表示字体,传入定义好的字体 ```
` 4.保存图片对象
# './images/change.png''./images/'保存的图片路径,../change.png须要保存的图片名 # 'png' 图片保存的格式 image.save('./images/change.png', 'png')