search
HomeBackend DevelopmentPython TutorialIntroducing python application learning qrcode to generate QR codes

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

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,              #二维码边框宽度    )

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

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

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

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

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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment