%matplotlib inline
from PIL import Image, ImageDraw, ImageFont
import random
# 獲取字體以及大小
font = ImageFont.truetype("../../font/Arial.ttf", size=30)
# 隨機數字:
def rndInt():
return str(random.randint(0, 9))
# 隨機顏色1:
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 隨機顏色2:
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
# 基礎Settings:
width, height = 60 * 5, 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 創建Draw對象:
draw = ImageDraw.Draw(image)
# 填充每個像素:
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rndColor())
# 輸出文字:
for t in range(5):
draw.text((60 * t + 10, 10), rndInt(), font=font, fill=rndColor2())
# # 模糊:
# from PIL import ImageFilter
# image = image.filter(ImageFilter.BLUR)
# 保存到硬盤,名爲verify.png格式爲png的圖片
image.save(open('../../tmp/num_verify.png', 'wb'), 'png')
image
參考:https://www.liaoxuefeng.com/wiki/897692888725344/966759628285152