图片上画线条
import sysfrom PIL import Image,ImageDrawim = Image.open("th.png")draw = ImageDraw.Draw(im) #实例化一个对象draw.line((0, 0) + im.size, fill=128, width=5) #线的起点和终点,线宽draw.line((0, im.size[1], im.size[0], 0), fill=128)draw.line((0,im.size[1]/2)+(im.size[0]/2,im.size[1]), fill=128, width=5)im.show()
图片上写字
from PIL import Image, ImageDraw, ImageFont# get an imagebase = Image.open('th.jpg').convert('RGBA')# make a blank image for the text, initialized to transparent text colortxt = Image.new('RGBA', base.size, (255,255,255,0))# get a font 需要在C:\Windows\Fonts拷贝一份字体文件 当前脚本路径下fnt = ImageFont.truetype('cambriai.ttf', 40)# get a drawing contextd = ImageDraw.Draw(txt)# draw text, half opacityd.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))# draw text, full opacityd.text((10,60), "World", font=fnt, fill=(255,255,255,255))fillcolor = "#ff0000" #字体颜色d.text((base.size[0]-20,10), "4", font=fnt, fill=fillcolor)out = Image.alpha_composite(base, txt)out.show()
参考官方文档 https://pillow.readthedocs.io/en/stable/reference/Image.html