Home > Backend Development > Python Tutorial > Introducing python application learning qrcode to generate QR codes

Introducing python application learning qrcode to generate QR codes

coldplay.xixi
Release: 2021-02-23 10:14:14
forward
2908 people have browsed it

Introducing python application learning qrcode to generate QR codes

Free learning recommendations: python video tutorial

Python applied learning (1) - qrcode generates QR code

  • Preface
  • 1. Preparation
  • 2. Code writing
    • 1.Introduce the library
    • 2.Configure initialization parameters
    • 3.Get the QR code object
    • 4.In the QR code Place the logo
    • 5. Configure the corresponding information and call the function
    • 6. Complete code
  • Finally

Preface

This article uses python to generate a QR code that you want, in which the code is annotated and answers to relevant knowledge


1. Preparation

1. python environment

2. The involved python library requires pip install Package name Installation

pip install qrcode
pip install pillow

2. Code writing

1.Introduce the library

import qrcodefrom PIL import Imageimport osimport sys
Copy after login

2.Configure initialization parameters

 qr = qrcode.QRCode(
        version=2,  #25*25     二维码的版本号,每一个版本号对应一个尺寸,这里尺寸不是图片的大小而的是二维码长宽被分成的份数
        error_correction=qrcode.constants.ERROR_CORRECT_H,     #纠错容量,指二维码不完整时可以正常识别出原信息的概率(ERROR_CORRECT_H的纠错率最高)
        box_size=8,            #生成图片的像素
        border=1,              #二维码边框宽度    )
Copy after login

3. Get the QR code object

qr.add_data(string)  **#string为想要打开的链接**
    qr.make(fit=True)    #用make()方法生成图片
    img = qr.make_image(fill_color = 'black',back_color = 'white')  #得到二维码对象,并可以通过修改fill_color、back_color参数来调整小格子颜色和背景色
    img = img.convert("RGBA")  #将图片转换为RGBA格式
Copy after login

4. In the QR code Place the logo

if logo and os.path.exists(logo):
        try:
            icon = Image.open(logo)
            img_w, img_h = img.size  #img_w、img_h是二维码的尺寸
        except Exception as e:
            print(e) 
            sys.exit(1)
        factor = 4
        size_w = int(img_w / factor)
        size_h = int(img_h / factor)

        icon_w, icon_h = icon.size   #icon_W、icon_h是logo原始的尺寸        if icon_w > size_w:          #size_W、size_h是二维码尺寸的1/factor
            icon_w = size_w        if icon_h > size_h:
            icon_h = size_h
        icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)   #antialias是平滑处理
        # 保证二维码大小不超过二维码大小的1/factor

        w = int((img_w - icon_w) / 2)  #计算logo在二维码中的相对位置
        h = int((img_h - icon_h) / 2)
        icon = icon.convert("RGBA")
        img.paste(icon, (w, h), icon)  #根据相对位置w、h将logo放到二维码图片上,所以说实际是logo并不是二维码的一部分,会遮挡二维码的一部分,不能太大,否则无法识别
Copy after login

5. Configure the corresponding information and call the function

if __name__ == "__main__":
    info = "https://blog.csdn.net/weixin_45386875/article/details/113766276"            #二维码的链接
    pic_path = "qr.png"                       #生成的图片保存文件
    logo_path = "logo.png"                    #logo的文件名    gen_qrcode(info, pic_path,logo_path )     #调用函数
Copy after login

6. Complete code

import qrcodefrom PIL import Imageimport osimport sysdef gen_qrcode(string, path, logo=""):
    """
    生成中间带logo的二维码
    需要安装qrcode, PIL库
    @参数 string: 二维码字符串
    @参数 path: 生成的二维码保存路径
    @参数 logo: logo文件路径
    @return: None
    """
    qr = qrcode.QRCode(
        version=2,  #25*25     二维码的版本号,每一个版本号对应一个尺寸,这里尺寸不是图片的大小而的是二维码长宽被分成的份数
        error_correction=qrcode.constants.ERROR_CORRECT_H,     #纠错容量,指二维码不完整时可以正常识别出原信息的概率(ERROR_CORRECT_H的纠错率最高)
        box_size=8,    #生成图片的像素
        border=1,      #二维码边框宽度
    )
    qr.add_data(string)  #string为想要打开的链接
    qr.make(fit=True)    #用make()方法生成图片
    img = qr.make_image(fill_color = 'black',back_color = 'white')  #得到二维码对象,并可以通过修改fill_color、back_color参数来调整小格子颜色和背景色
    img = img.convert("RGBA")  #将图片转换为RGBA格式
    if logo and os.path.exists(logo):
        try:
            icon = Image.open(logo)
            img_w, img_h = img.size  #img_w、img_h是二维码的尺寸
        except Exception as e:
            print(e) 
            sys.exit(1)
        factor = 4
        size_w = int(img_w / factor)
        size_h = int(img_h / factor)

        icon_w, icon_h = icon.size   #icon_W、icon_h是logo原始的尺寸
        if icon_w > size_w:          #size_W、size_h是二维码尺寸的1/factor
            icon_w = size_w        if icon_h > size_h:
            icon_h = size_h
        icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)   #antialias是平滑处理
        # 保证二维码大小不超过二维码大小的1/factor

        w = int((img_w - icon_w) / 2)  #计算logo在二维码中的相对位置
        h = int((img_h - icon_h) / 2)
        icon = icon.convert("RGBA")
        img.paste(icon, (w, h), icon)  #根据相对位置w、h将logo放到二维码图片上,所以说实际是logo并不是二维码的一部分,会遮挡二维码的一部分,不能太大,否则无法识别
    img.save(path)
    # 调用系统命令打开图片
    # xdg - open(opens a file or URL in the user's preferred application)
    #os.system('xdg-open %s' %(path)) #这是Linux系统的命令
    os.startfile(path) #windows 下打开文件if __name__ == "__main__":
    info = "https://blog.csdn.net/weixin_45386875?spm=1010.2135.3001.5343"            #二维码的链接
    pic_path = "qr.png"                       #生成的图片保存文件
    logo_path = "logo.png"                    #logo的文件名
    gen_qrcode(info, pic_path,logo_path )     #调用函数
Copy after login

Related free learning recommendations: python tutorial(Video)

The above is the detailed content of Introducing python application learning qrcode to generate QR codes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template