Use PIL to generate text images

Install PIL

pip3 install pillow

Use PIL

from PIL import Image, ImageFont, ImageDraw

# image = Image.open('bg.jp') # 读取图片
image = Image.new('RGB', (250, 250), (255,255,255)) # 设置画布大小及背景色
iwidth, iheight = image.size # 获取画布高宽
font = ImageFont.truetype('consola.ttf', 110) # 设置字体及字号
draw = ImageDraw.Draw(image)

fwidth, fheight = draw.textsize('22', font) # 获取文字高宽

fontx = (iwidth - fwidth - font.getoffset('22')[0]) / 2
fonty = (iheight - fheight - font.getoffset('22')[1]) / 2

draw.text((fontx, fonty), '22', 'black', font)
image.save('1.jpg') # 保存图片

Guess you like

Origin blog.51cto.com/14284354/2542533