直接上高速
# -*-coding:utf-8 -*-
'''
@Time: 2021/7/29 15:14
@desc:
'''
from PIL import Image
import random
import time
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
class CheckCode:
'''
生成图片验证码
'''
def generation_code(self):
'''
生成随机字符
:return:
'''
valid_code = ''
for i in range(4):
string_low = chr(random.randint(97, 122))
string_upper = chr(random.randint(65, 90))
num = str(random.randint(0,9))
code = random.choice([string_low, string_upper, num])
valid_code += code
return valid_code
def get_random_color(self):
'''
生成随机颜色
:return:
'''
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
def generation_img(self):
'''
生成图片
:return:
'''
img = Image.new("RGB", (200, 40), color=self.get_random_color())
draw = ImageDraw.Draw(img)
font = ImageFont.truetype('Arial.ttf', size=30)
check_code = self.generation_code()
i = 1
# 写入文本
for c in check_code:
draw.text((i*40, 4), c, self.get_random_color(), font=font )
i = i+1
# 设置图片宽高
width = 200
height = 40
# 写干扰点
for i in range(40):
draw.point([random.randint(0, width), random.randint(0, height)], fill=self.get_random_color())
# 画线干扰
for i in range(5):
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=self.get_random_color())
# 写干扰圆圈
for i in range(5):
draw.point([random.randint(0, width), random.randint(0, height)], fill=self.get_random_color())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.get_random_color())
return img, check_code
img, check_code = CheckCode().generation_img()
# filename = str(int(time.time())) + ".png"
# with open(filename, "wb") as w:
# img.save(w, format="png")
# 将验证图片写入内存中, 不用存储服务器
f = BytesIO()
img.save(f, "png")
img.show()
print f.getvalue()
print check_code