zoukankan      html  css  js  c++  java
  • 验证码:滑动,图片

    @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')
  • 相关阅读:
    关于fill_parent ,wrap_content ,match_parent区别
    开发第六天
    开发第五天
    关于Android创建虚拟机出现Failed to allocate memory: 8解决办法
    第十一周总结
    开发第四天
    开发第三天
    开发第二天
    开发第一天
    用户场景分析
  • 原文地址:https://www.cnblogs.com/zhaoweihang/p/9282262.html
Copyright © 2011-2022 走看看