zoukankan      html  css  js  c++  java
  • Django 生成验证码或二维码 pillow模块

    一、安装PIL
    • PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,API也非常简单易用。
       
      PIL模块只支持到Python 2.7,许久没更新了,在python 3.* 版本上使用Pillow模块
       
      安装Pillow
       
      pip install pillow
    二、pillow 基本使用
    • 图像缩放
    
    from PIL import Image
    
    # 当前路径打开一个jpg图像文件
    img = Image.open('test.jpg')
    # 获得图像尺寸:
    w, h = img.size
    print('图片长宽: {}-{}' .format(w, h))
    # 缩放到50%:
    img.thumbnail((w//2, h//2))
    print('缩小50%: {}-{}'.format(w//2, h//2))
    # 把缩放后的图像用jpeg格式当前路径保存:
    img.save('myimg.jpg', 'jpeg')
    
    • 切片、旋转、滤镜、输出文字、调色板等一应俱全。

    比如,模糊效果也只需几行代码:

    from PIL import Image, ImageFilter
    
    # 打开一个jpg图像文件,注意是当前路径:
    im = Image.open('test.jpg')
    # 应用模糊滤镜:
    im2 = im.filter(ImageFilter.BLUR)
    im2.save('blur.jpg', 'jpeg')
    
    三、pillow制作验证码
    • 生成验证码及验证码图片
    #vericode.py
    
    
    import random
    
    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont
    from PIL import ImageFilter
    
    
    def get_chars_str():
        '''
        :return:验证码字符集合 
        '''
        _letter_cases = "abcdefghjkmnpqrstuvwxy"  # 小写字母,去除可能干扰的i,l,o,z
        _upper_cases = _letter_cases.upper()  # 大写字母
        _numbers = ''.join(map(str, range(3, 10)))  # 数字
        init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
        return init_chars
    
    def create_validate_code(size=(120, 30),
                             chars=get_chars_str(),
                             img_type="JPEG",
                             mode="RGB",
                             bg_color=(255, 255, 255),
                             fg_color=(0, 0, 255),
                             font_size=18,
                             font_type=r"E:myblogutilsArial.ttf",  #我的是全路径  可以自己使用 os 模块自动拼接  没有字体去下载 Arial.ttf字体
                             length=4,
                             draw_lines=True,
                             n_line=(1, 2),
                             draw_points=True,
                             point_chance=2):
       """
         生成验证码图片
        :param size: 图片的大小,格式(宽,高),默认为(120, 30)
        :param chars: 允许的字符集合,格式字符串
        :param img_type: 图片保存的格式,默认JPEG,可选的为GIF,JPEG,TIFF,PNG
        :param mode: 图片模式,默认为RGB
        :param bg_color: 背景颜色,默认为白色
        :param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
        :param font_size: 验证码字体大小
        :param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
        :param length: 验证码字符个数
        :param draw_lines: 是否划干扰线
        :param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
        :param draw_points: 是否画干扰点
        :param point_chance: 干扰点出现的概率,大小范围[0, 100]
        :return: [0]: PIL Image实例
        :return: [1]: 验证码图片中的字符串
        """
        width, height = size  # 宽高
        # 创建图形
        img = Image.new(mode, size, bg_color)
        draw = ImageDraw.Draw(img)  # 创建画笔
    
        def get_chars():
            """生成给定长度的字符串,返回列表格式"""
            return random.sample(chars, length)
    
        def create_lines():
            """绘制干扰线"""
            line_num = random.randint(*n_line)  # 干扰线条数
    
            for i in range(line_num):
                # 起始点
                begin = (random.randint(0, size[0]), random.randint(0, size[1]))
                # 结束点
                end = (random.randint(0, size[0]), random.randint(0, size[1]))
                draw.line([begin, end], fill=(0, 0, 0))
    
        def create_points():
            """绘制干扰点"""
            chance = min(100, max(0, int(point_chance)))  # 大小限制在[0, 100]
    
            for w in range(width):
                for h in range(height):
                    tmp = random.randint(0, 100)
                    if tmp > 100 - chance:
                        draw.point((w, h), fill=(0, 0, 0))
    
        def create_strs():
            """绘制验证码字符"""
            c_chars = get_chars()
            strs = ' %s ' % ' '.join(c_chars)  # 每个字符前后以空格隔开
    
            font = ImageFont.truetype(font_type, font_size)
            font_width, font_height = font.getsize(strs)
    
            draw.text(((width - font_width) / 3, (height - font_height) / 3),
                      strs, font=font, fill=fg_color)
    
            return ''.join(c_chars)
    
        if draw_lines:
            create_lines()
        if draw_points:
            create_points()
        strs = create_strs()
    
        # 图形扭曲参数
        params = [1 - float(random.randint(1, 2)) / 100,
                  0,
                  0,
                  0,
                  1 - float(random.randint(1, 10)) / 100,
                  float(random.randint(1, 2)) / 500,
                  0.001,
                  float(random.randint(1, 2)) / 500
                  ]
        img = img.transform(size, Image.PERSPECTIVE, params)  # 创建扭曲
    
        img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 滤镜,边界加强(阈值更大)
    
        return img, strs
    
    2.2 视图业务逻辑函数块
    • 验证码请求url 为: path("check-code.html", views.check_code),
    from io import BytesIO
    
    from django.shortcuts import HttpResponse
    
    def check_code(request):
        """返回验证码图片"""
        image, code = create_validate_code(size=(80,30))
        f = BytesIO()
        request.session["check_code"] = code
        request.session.set_expiry(30)
        image.save(f,"JPEG") #保存图片
        return HttpResponse(f.getvalue()) #返回图片
    
    2.3 前端代码块
     
    <div class="" style=" 275px;height: 50px;">
        验证码:<br />
        <input Class="validate" id="check_code" name="check_code" style="60px;height: 9px;" type="text" placeholder="验证码" />
        <img id="idf_img" src="/blog/check-code.html" style="float: right;  60px; height: 24px; padding-top: 7px;"/>
    </div>
    
    三、qrcode制作二维码
    • import qrcode

    • 参数含义:
      参数 version 表示生成二维码的尺寸大小,取值范围是 1 至 40,
      最小尺寸 1 会生成 21 * 21 的二维码,version 每增加 1,生成的二维码就会添加 4 尺寸,
      例如 version 是 2,则生成 25 * 25 的二维码。
      参数 error_correction 指定二维码的容错系数,分别有以下4个系数:
      1.ERROR_CORRECT_L: 7%的字码可被容错
      2.ERROR_CORRECT_M: 15%的字码可被容错
      3.ERROR_CORRECT_Q: 25%的字码可被容错
      4.ERROR_CORRECT_H: 30%的字码可被容错
      可以生成二维码图片,根据参数
      参数 box_size 表示二维码里每个格子的像素大小。
      参数 border 表示边框的格子厚度是多少(默认是4)。

    def create_qr_code(data, version=7, box_size=10, border=4):
        """
        生成普通二维码
        :param data: 你要生成二维码的数据,如 url 网址 或者 "我爱你成元"
        :return: img 返回的是图片,如果需要保存就 image.save()
        """
    
        qr = qrcode.QRCode(
            version=version,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=box_size,
            border=border
        )
        qr.add_data(data)
        #qr.add_data("我爱你成元")
        qr.make(fit=True)
        img = qr.make_image()
        return img
    
    3.2 生成中心带图片的二维码
    • from PIL import Image
      import qrcode
    from PIL import Image
    import qrcode
    
    - data 第一个参数为二维码内容, path 第二个参数将要添加到中间的图片路径
    
    def create_mid_pic_code(data, path):
        """
        生成中间带图片的二维码
        :param data: 二维码内容
        :param path: 将要放在二维码中间的图片路径
        :return: img 返回制作好的图片
        """
        qr = qrcode.QRCode(
            version=4,
            error_correction=qrcode.constants.ERROR_CORRECT_H,
            box_size=10,
            border=2
        )
        qr.add_data(data)
        qr.make(fit=True)
    
        img = qr.make_image()
        img = img.convert("RGBA")
        
        # 打开要添加的图片文件对象
        picture = Image.open(path)
    
        img_w, img_h = img.size
        factor = 4
        size_w = int(img_w / factor)
        size_h = int(img_h / factor)
    
        picture_w, picture_h = picture.size
        if picture_w > size_w:
            picture_w = size_w
        if picture_h > size_h:
            picture_h = size_h
            picture = picture.resize((picture_w, picture_h), Image.ANTIALIAS)
    
        w = int((img_w - picture_w) / 2)
        h = int((img_h - picture_h) / 2)
        img.paste(picture, (w, h), picture)
    
        return img
    
  • 相关阅读:
    移动端(H5)弹框组件--简单--实用--不依赖jQuery
    jquery attr()和prop()方法的区别
    jQuery选择器
    Tomcat&Web程序结构&Http协议(一)
    Javascript&DOM(三)
    html&CSS代码篇(二)
    html&css入门篇(一)
    『一本通』区间DP
    『P1549』棋盘问题
    『USACO08OCT]』Watering Hole
  • 原文地址:https://www.cnblogs.com/shiqi17/p/9688603.html
Copyright © 2011-2022 走看看