Python study notes 8- use qrcode module generates ordinary two-dimensional code and two-dimensional code with icons

Two-dimensional bar code, also known as two-dimensional, two-dimensional code common to QR Code, QR stands for Quick Response, is a super popular form of encoding on mobile devices in recent years, it is more than the traditional Bar Code bar code can store more the information can also be expressed more data types.

Official website on github:

https://github.com/lincolnloop/python-qrcode#advanced-usage

A, qrcode module mounting introduced

The CMD mode, the module mounting qrcode

python -m pip install requests

Then introducing qrcode module in python.

import qrcode

Second, the simple two-dimensional code generation

The simplest wording:

import qrcode

data = "https://www.baidu.com"   # data 可以是链接,也可以是普通字符串。
erweima = qrcode.make( data )
print( erweima )  # <class 'qrcode.image.pil.PilImage'>
erweima.save("1.png")  # 保存图片。其实利用了PIL对象的 save 方法

qrcode objects can make method of generating a two-dimensional code data corresponding to the image data, the PIL is a graphical object.

The two-dimensional code generated as follows:

Micro-channel or mobile browser to scan the two-dimensional code, the page will jump to Baidu.

In essence, sweep the two-dimensional code is to get the content, without any jump page . Micro-channel or a mobile browser will jump, because if they added a two-dimensional code scanning result url will automatically jump code caused.

Also this:

import os, qrcode
data = "https://www.baidu.com"
erweima = qrcode.make( data )
with open('1.png', 'wb') as f:  # 利用 os 模块的open方法存储图片
    erweima.save(f)

Third, the two-dimensional code to generate more detailed configuration

The general steps

  1. Creating objects QRCode

  2. add_data is () to add data

  3. make_image () to create a two-dimensional code (im return type of picture object. You can change the color of the two-dimensional code here)

  4. Automatically open the picture, im.show (); or two-dimensional code saved to the specified location.

Simplified version:

import qrcode,os

data = "https://www.baidu.com"   # 二维码数据
ewm = qrcode.QRCode()            # 创建QRCode对象,一切采用默认值
ewm.add_data(data)				 # 添加数据
ewm_img = ewm.make_image()       # 生成二维码图像
ewm_img.show()					 # 直接显示图像
with open("test_qr.jpg","wb")  as f:   # 保存图像到指定位置
    ewm_img.save(f)

Extended Version:

import qrcode,os

# 设置二维码的数据
data = "https://www.baidu.com"
# 创建QRCode对象
ewm = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
# 添加数据到二维码中
ewm.add_data(data=data)
# 更改二维码的颜色,默认是黑色
ewm.make(fit=True)
ewm_img = ewm.make_image(fill_color="#ff3300", back_color="white")
# 显示二维码
ewm_img.show()
with open("test_qr.jpg","wb")  as f:   # 保存图像到指定位置
    ewm_img.save(f)

Parameters and Method Description

QRCode object parameter description:

  • Version : an integer ranging from 1 to 40, for controlling the size of the two-dimensional code (the minimum value is 1, is a matrix of 21 × 21), if you want the automatic program generation, and the value is set to None used make the method fit = True parameter.

  • error_correction : two-dimensional code error rate allowable, you can choose four constants:

    1. ERROR_CORRECT_L: 7% or less of the error will be corrected

    2. ERROR_CORRECT_M: 15% or less of the error will be corrected [defaults]

    3. ERROR_CORRECT_Q: 25% or less of the error will be corrected

    4. ERROR_CORRECT_H: 30% or less of the error will be corrected

  • boxsize number of pixels in a two-dimensional code for each point (block) of:

  • border : the small number of lattice two-dimensional code to picture frame, the default is 4, and the relevant provisions of a minimum of 4

Method Description:

  • add_data is (Data, 20 is Optimize =) : to add data to convert datathe parameter; If the optimizeoptimization parameters, data will be split into a plurality of blocks to be optimized to find the value of a length at least sufficient to compact way generate two-dimensional code. Is set to "0" to avoid optimization.

  • the make (Fit = True) : When the fitparameter is true or not given QRCode target versionparameter will be called best_fitmethod to find the minimum sized data. If the object QRCode not set mask_pattern, it will call the best_mask_patternmethod to find the find the most effective mask pattern. Finally, the data is transmitted to makeImplgenerating a two-dimensional code method. And qrcodethe body of makethe method is not the same, this method has no return value.

  • make_image (fill_color = None, BACK_COLOR = None, image_factory = None) : create a two-dimensional code image and return to the default image for the PIL. Color values can be words, it can be #RRGGBB mode. General on the use of the previous two parameters, the default behind it, do not get so complicated.

Other methods:

  • the Clear : Clear data

  • get_matrix : returns an array of two-dimensional code.

  • print_ascii (OUT = None, TTY = False, Rate History For Converting = False) : This method is used in the form of characters to draw two-dimensional code output, but generally sweep sweep time does not come out very often appears to be a mess, look at it by the way.

import qrcode,os
# 创建QRCode对象
ewm = qrcode.QRCode()
# 设置二维码数据, 并添加到二维码中
data = "https://www.baidu.com"
ewm.add_data(data=data)

ewm.make(fit=True)
# ewm.clear()   # 清空数据
ewm_list = ewm.get_matrix()  # 获取二维码数组
# 更改二维码的颜色,默认是黑色
ewm_img = ewm.make_image(fill_color="#ff3300", back_color="white")
# 打印字符二维码
ewm.print_ascii()  # 根本扫不出来,也就是看看样子。
# 打印二维码数组
print(ewm_list)
# 显示二维码
ewm_img.show()    # 如果数据被clear了,会有个二维码,扫它什么都不会发生

Fourth, the intermediate two-dimensional code with icons

Simply put, it is to use small icons directly attached to the two-dimensional code. Although the two-dimensional code is covered by a part, but because there is a two-dimensional code fault tolerance, it can still be swept out . Therefore, it does not recommend the icon is too big, too two-dimensional code fault tolerance does not.

Therefore, the two-dimensional code with icons, generally set high fault rate (ERROR_CORRECT_H).

After others test their own measure, small picture is two-dimensional code picture width and height of one sixth most appropriate.

Normally the icon is placed in the middle of the two-dimensional code:

X coordinate of the upper left corner is green block (two-dimensional code image width - Icon width) / 2, y coordinate empathy push.

So the whole idea is:

  1. To obtain two-dimensional code, and width and height to get it;

  2. Width and height using the two-dimensional code, calculates the width and height of the icon;

  3. Image.open method using the PIL, open the icon image is scaled to the appropriate size.

  4. The icon "paste" into the two-dimensional code: Use PIL object paste paste method

  5. Save the integrated picture down: use the save method PIL object.

For example Code: ready to implement a icon file, square . I am here girl.jpg file.

# -*- coding:utf-8 -*-
import os , qrcode
from PIL import  Image

import qrcode,os
# 创建QRCode对象
ewm = qrcode.QRCode(
    version=5,
    error_correction=qrcode.constants.ERROR_CORRECT_H,
    box_size=10,
    border=4,
)
# 设置二维码数据, 并添加到二维码中
data = "https://www.baidu.com"
ewm.add_data(data=data)
# 更改二维码的颜色,默认是黑色。得到的结果是 PIL 图像对象
ewm.make(fit=True) # 让二维码得到一个适合的大小值。
ewm_img = ewm.make_image(fill_color="#ff3300", back_color="white")
# 获取二维码大小:宽,高
ewm_size = ewm_img.size
ewm_size_w ,ewm_size_h = ewm_size

# 打开图标文件,并获取图标的大小,重新设定图标大小
# 这里设置icon宽高为二维码的 6分之一。
s = 6
icon = Image.open("girl.png")
# 设置小图标的大小,缩放的时候尺寸必须是整数,否则报错
icon_w,icon_h = int(ewm_size_w/s) ,int(ewm_size_h/s)
icon_small = icon.resize( (icon_w ,icon_h) ,Image.ANTIALIAS)  # Image.ANTIALIAS 画面平滑缩放
# 获取粘贴小图标的坐标,必须整数,否则粘贴的时候,报错
icon_x, icon_y = int( (ewm_size_w-icon_w)/2 ), int( (ewm_size_h-icon_h)/2)
# 把图标“粘贴”到二维码上正中间。
ewm_img.paste( icon_small,(icon_x,icon_y)  )

# 显示二维码
ewm_img.show()    # 如果数据被clear了,会有个二维码,扫它什么都不会发生
ewm_img.save("girl_ewm.jpg")

Here used PIL Image object. It uses the open (), resize (), paste () method. They can not say here in detail, specifically to see the comment, it is relatively simple.

Have the opportunity to write notes of a PIL. FIG final results: girl's original offer -

Published 86 original articles · won praise 146 · views 50000 +

Guess you like

Origin blog.csdn.net/weixin_42703239/article/details/104349417