安装依赖
pip install pillow
1、新建一张300*300的白色画布
# -*- coding: utf-8 -*-
from PIL import Image
# 参数:模式、大小、颜色
image = Image.new(mode="RGB", size=(300, 300), color="white")
image.save("1.png")
图片:
2、画布上加一些文字
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
# 参数:模式、大小、颜色
image = Image.new(mode="RGB", size=(300, 300), color="white")
# 添加文字
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(font='PingFang.ttc', size=40)
# 参数:位置、文本、填充、字体
draw.text(xy=(100, 100), text='demo', fill=(255, 0, 0), font=font)
image.save("1.png")
3、裁剪上面的图片,把文字部分裁出来
# 裁剪 左上角和右下角坐标 (left, upper, right, lower)
sub_image = image.crop(box=(90, 100, 210, 160))
4、为了好看,我在文字边上画个框,将裁剪下来的文字张贴到图片另外的位置
# -*- coding: utf-8 -*-
from PIL import Image, ImageDraw, ImageFont
# 参数:模式、大小、颜色
image = Image.new(mode="RGB", size=(300, 300), color="white")
# 添加文字
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(font='PingFang.ttc', size=40)
# 参数:位置、文本、填充、字体
draw.text(xy=(100, 100), text='demo', fill=(255, 0, 0), font=font)
# 画个边框为1的红色矩形框
draw.rectangle(xy=(90, 100, 210, 160), fill=None, outline="red", width=1)
# 裁剪 左上角和右下角坐标 (left, upper, right, lower)
sub_image = image.crop(box=(90, 100, 220, 170))
# 裁剪下来的子图粘贴到原图上
image.paste(im=sub_image, box=(90, 200))
image.save("1.png")
参考
- 如何使用python的Pillow模块新建图像
- 如何使用python的Pillow模块复制粘贴图像
- python如何使用pil画一个矩形