驗證碼:滑動,圖片
阿新 • • 發佈:2018-07-09
http 格式 request tmp 一個 val edr cache true
@never_cache # 永不使用緩存,每次請求都是從新運行代碼
def v_code(request):
from PIL import Image, ImageDraw, ImageFont
import random
# 這是一個產生隨機顏色的函數
def get_color():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
img_obj = Image.new(
"RGB", # 格式
(250, 35), # 尺寸
color=get_color()
)
# 在圖片中加文字
# 生成一個畫筆對象
draw_obj = ImageDraw.Draw(img_obj)
# 加載字體文件
font_obj = ImageFont.truetype("static/font/kumo.ttf", size=28)
# 生成隨機5位字符串
l = []
for i in range(5):
n = str(random.randint(0, 9))
m = chr(random.randint(65, 90))
s = chr(random.randint(97, 122))
r = random.choice([n, m, s])
l.append(r)
draw_obj.text(
(i * 48 + 20, 0), # 字體在圖片中的位置
r, # 內容
get_color(), # 顏色
font=font_obj
)
# 5位隨機驗證碼
v_code_str = ‘‘.join(l)
# 每個請求對應自己的驗證碼
request.session[‘v_code‘] = v_code_str.upper()
# 加幹擾線
# width = 250 # 圖片寬度(防止越界)
# height = 35
# for i in range(2):
# x1 = random.randint(0, width)
# x2 = random.randint(0, width)
# y1 = random.randint(0, height)
# y2 = random.randint(0, height)
# draw_obj.line((x1, y1, x2, y2), fill=get_color())
#
# # 加幹擾點
# for i in range(2):
# draw_obj.point([random.randint(0, width), random.randint(0, height)], fill=get_color())
# x = random.randint(0, width)
# y = random.randint(0, height)
# draw_obj.arc((x, y, x+4, y+4), 0, 90, fill=get_color())
# 第一版:將生成的圖片保存到文件中
# with open(‘aa.png‘,‘wb‘)as f:
# img_obj.save(f,‘png‘)
# print(‘圖片已經生成‘)
# with open(‘aa.png‘,‘rb‘)as f:
# return HttpResponse(data,content_type=‘image/png‘)
# 第二版:在內存中保存圖片
from io import BytesIO
tmp = BytesIO() # 生成一個io對象
img_obj.save(tmp, ‘png‘)
data = tmp.getvalue()
return HttpResponse(data, content_type=‘image/png‘)
驗證碼:滑動,圖片