python生成图片验证码

Posted 阿强Wwlt

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python生成图片验证码相关的知识,希望对你有一定的参考价值。

import PIL

from PIL import Image
from PIL import ImageDraw,ImageFont
import random
def get_random_color():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))


image = Image.new("RGB", (250, 40), get_random_color())

# 生成五个随机字符
draw=ImageDraw.Draw(image)
font=ImageFont.truetype("blog/static/font/kumo.ttf",size=32)
temp=[]
for i in range(5):
random_num=str(random.randint(0,9))
random_low_alpha=chr(random.randint(97,122))
random_upper_alpha=chr(random.randint(65,90))
random_char=random.choice([random_num,random_low_alpha,random_upper_alpha])
draw.text((24+i*36,0),random_char,get_random_color(),font=font)

# 保存随机字符
temp.append(random_char)

# 噪点噪线
# width=250
# height=40
# for i in range(100):
# x1=random.randint(0,width)
# x2=random.randint(0,width)
# y1=random.randint(0,height)
# y2=random.randint(0,height)
# draw.line((x1,y1,x2,y2),fill=get_random_color())
#
# for i in range(400):
# draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
# x = random.randint(0, width)
# y = random.randint(0, height)
# draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())

# 在内存生成图片
from io import BytesIO
f = BytesIO()
image.save(f,"png")
data = f.getvalue()
f.close()

 

# ["a","2","2","s"]
valid_str="".join(temp) # "a22s"
print("valid_str",valid_str)

request.session["valid_str"]=valid_str

return HttpResponse(data)

以上是关于python生成图片验证码的主要内容,如果未能解决你的问题,请参考以下文章

python生成图片验证码

python生成验证码,文字转换为图片

第二百七十节,Tornado框架-生成验证码图片,以及验证码结合Session验证

python 蟒蛇生成图片验证码

PIL 生成随机验证码图片

python 随机生成图片验证码背景RGB-浅色或者深色