一、方式一

代码
import random
from PIL import Image, ImageDraw, ImageFont
def get_random_color():
"""获取随机颜色"""
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
def get_valid_code():
"""生成随机验证码"""
image = Image.new("RGB", (136, 36), "rgb(255, 255, 255)")
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("monaco.ttf", size=34) #字体和大小
# 生成4个随机字母或数字
valid_list = []
for i in range(1, 5):
number = str(random.randint(0, 9))
lower_letter = chr(random.randint(97, 122))
upper_letter = chr(random.randint(65, 90))
random_char = random.choice([number, lower_letter, upper_letter])
draw.text((i*20, 0), random_char, fill="black", font=font)
valid_list.append(random_char)
width = 136
height = 36
# 画干扰线
for i in range(3):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=get_random_color())
# 画干扰点
for i in range(100):
x = random.randint(0, width)
y = random.randint(0, height)
draw.point([x, y], fill=get_random_color())
valid_str = "".join(valid_list)
# valid_str保存在session中,在登录时用来做验证
# request.session["valid_str"] = valid_str
return image, valid_str
if __name__ == "__main__":
image, code = get_valid_code()
# 1、直接打开
image.show()
# 2、保存在本地
# with open("code.png", "wb") as f:
# image.save(f, format="png")
# 3、写入内存(Python3)
# import io
# stream = io.BytesIO()
# image.save(stream, "png")
# valid_image = stream.getvalue()
# stream.close()
# 从内存中获取刚生成的验证码图片,返回给前端
# return HttpResponse(valid_image)