<pre>import string
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from datetime import *
import uuid
import time
from PIL import ImageFilter
# 创建图片
image = Image.new("RGB", (180, 60), "white")
# 创建对象
draw = ImageDraw.Draw(image)
def rand_txt():
chars = string.ascii_letters + string.digits
s = [random.choice(chars) for j in range(5)]
m = ('{0}\n'.format(''.join(s)))
return m
def rand_color():
randcolor=(random.randint(129, 255), random.randint(129, 255), random.randint(129, 255))
return randcolor
def rand_txtcolor():
txtclor=(random.randint(32, 128), random.randint(32, 128), random.randint(32, 128))
return txtclor
def rand_font():
f6 = ImageFont.truetype("C:\Windows\Fonts\STXINGKA.TTF", 48)
f5 = ImageFont.truetype("C:\Windows\Fonts\LetterGothicStd-BoldSlanted.otf", 48)
f4 = ImageFont.truetype("C:\Windows\Fonts\ONYX.TTF", 48)
f3 = ImageFont.truetype("C:\Windows\Fonts\LHANDW.TTF", 48)
f2 = ImageFont.truetype("C:\Windows\Fonts\LithosPro-Regular.otf", 48)
f1 = ImageFont.truetype("C:\Windows\Fonts\FRSCRIPT.TTF", 48)
randfont = random.choice([f1,f2,f3,f4,f5,f6])
return randfont
def rand_name():#产生随机文件名
uuid_name = uuid.uuid4().time
randname ='F:\python\项目实战\验证码\yanzhenma\%s.png'%uuid_name
return randname
def rand_huabu():#遍历画布随机填充颜色
for x in range(180):
for y in range(60):
draw.point((x, y), fill=rand_color())
def rand_yanzhengma():
x = random.randint(0, 90)
for i in range(x):# 随机产生干扰线
x = random.randint(0, 180)
y = random.randint(0, 60)
xl = random.randint(0, 60)
yl = random.randint(0, 60)
draw.line((x, y, x + xl, y + yl), fill=rand_txtcolor())
final_font = rand_font()
draw.text((15, 10), rand_txt(), font=final_font, fill=rand_txtcolor())
image.save(rand_name(), 'PNG')#随机存在png文件中
if __name__ == '__main__':
for m in range(20): # 随机生成验证码
# 随机画布
rand_huabu()
rand_yanzhengma()
#image.show()#show验证码</pre>
[gallery ids="51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66" type="rectangular"]