Maison  >  Article  >  développement back-end  >  Présentation d'une application Python apprenant le qrcode pour générer des codes QR

Présentation d'une application Python apprenant le qrcode pour générer des codes QR

coldplay.xixi
coldplay.xixiavant
2021-02-23 10:14:142805parcourir

Présentation d'une application Python apprenant le qrcode pour générer des codes QR

Recommandations d'apprentissage gratuites : Tutoriel vidéo Python

Apprentissage des applications Python (1) - qrcode génère un code QR

  • Avant-propos
  • 1 Préparation
  • 2. >
  • 1. Importez la bibliothèque
    • 2. Configurez les paramètres d'initialisation
    • 3. Récupérez l'objet QR code
    • 4.
    • 5. Configurez les informations correspondantes et appelez la fonction
    • 6. Complétez le code
    Enfin
Avant-propos


Cet article utilise python pour générer un code QR que vous souhaitez, dans lequel le code est annoté et répond aux connaissances pertinentes



1. Préparation

1. Environnement python

2 Les bibliothèques python impliquées doivent être

installées.

pip install 包名

pip install qrcode
pip install pillow

2. Écriture du code

1. >
import qrcodefrom PIL import Imageimport osimport sys

2. Configurer les paramètres d'initialisation

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

3. Obtenez l'objet code QR


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格式

4 Placez le logo dans le code QR

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并不是二维码的一部分,会遮挡二维码的一部分,不能太大,否则无法识别

5. Configurez en conséquence Informations et fonction d'appel

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 )     #调用函数

6. Code complet

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 )     #调用函数

Recommandations d'apprentissage gratuites associées :

Tutoriel Python

(vidéo)

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer