美文网首页Python
python基于qrcode和Pillow二维码生成

python基于qrcode和Pillow二维码生成

作者: 醉枫浅墨 | 来源:发表于2018-01-16 16:55 被阅读20次

    因为项目需要,通过python的qrcode和Pillow库实现生成二维码。

    # coding:utf-8
    import qrcode
    from PIL import Image
    from django.conf import settings
    
    from common import constant
    from common.utils.utils_file import FileOperateUtil
    from common.utils.utils_qraphics import GraphicsUtil
    
    
    class QRCodeUtil(object):
        @staticmethod
        def create_qrcode(url, local_folder, local_file_name, qr_width=1280, qr_height=1280):
            """
            生成二维码
            :param url:              二维码对应链接地址
            :param local_folder:     二维码存放目录
            :param local_file_name:  二维码文件名
            :param qr_width:         宽度
            :param qr_height:        高度
            :return:
            """
            qr = qrcode.QRCode(
                version=1,
                # 设置容错率为最高
                error_correction=qrcode.ERROR_CORRECT_H,
                box_size=10,
                border=4,
            )
            qr.add_data(url)
            qr.make(fit=True)
    
            img = qr.make_image()
            # 设置二维码为彩色
            img = img.convert("RGBA")
            icon = Image.open(constant.APP_WEB_LOGO)
            w, h = img.size
            factor = 4
            size_w = int(w / factor)
            size_h = int(h / factor)
            icon_w, icon_h = icon.size
            if icon_w > size_w:
                icon_w = size_w
            if icon_h > size_h:
                icon_h = size_h
            icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
            w = int((w - icon_w) / 2)
            h = int((h - icon_h) / 2)
            icon = icon.convert("RGBA")
            newimg = Image.new("RGBA", (icon_w + 8, icon_h + 8), (255, 255, 255))
            img.paste(newimg, (w - 4, h - 4), newimg)
    
            img.paste(icon, (w, h), icon)
            real_file_folder = "%s/%s" % (settings.MEDIA_ROOT, local_folder)
            FileOperateUtil.validate_folder_exists(real_file_folder, is_create=True)
            real_file_path = "%s/%s" % (real_file_folder, local_file_name)
            img.save(real_file_path, quality=100)
            # 将图片放大到1280x1280
            GraphicsUtil.fixed_size(real_file_path, real_file_path, qr_width, qr_height)
    
    

    代码中有部分自定义常量,使用时自行修改即可...不完善之处,见谅!!!

    相关文章

      网友评论

        本文标题:python基于qrcode和Pillow二维码生成

        本文链接:https://www.haomeiwen.com/subject/ajteoxtx.html