图片上画线条
import sys
from PIL import Image,ImageDraw
im = 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 image
base = Image.open('th.jpg').convert('RGBA')
# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))
# get a font 需要在C:\Windows\Fonts拷贝一份字体文件 当前脚本路径下
fnt = ImageFont.truetype('cambriai.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)
# draw text, half opacity
d.text((10,10), "Hello", font=fnt, fill=(255,255,255,128))
# draw text, full opacity
d.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