After reading all the programs in the world, there is a code in my heart

The last time I played Sudoku ( Do you know how to do Sudoku by your friends? Python solves Sudoku in seconds to understand how to do it?) I was very angry with Pharaoh... This time, I directly took out the photo to see his reaction.

This time, Xiao Pang wants people to combine with each other, let's see what kind of trouble he makes.

As a qualified programmer, how can you not understand how the QR code is generated, how to parse it, and how to play? Without further ado, let's use Python today to play with this man-code-one.

demo environment

  • Operating system: windows10
  • python version: python 3.7
  • Code editor: pycharm 2018.2
  • Use modules: zxing, myqr, qrcode
  • Tips: The modules above are all installed using pip, and the modules they depend on will also be installed automatically. I believe you who know Python will not be too unfamiliar with pip.
pip install qrcode
pip install myqr
pip install zxing

Generate QR code using qrcode module

First let's generate a "Hello World".

import qrcode

def first_demo():
    # 存储的字符串
    qr = qrcode.make('Hello World')
    qr.get_image().show()

Through the above steps, you have completed this classic introduction. Take out your mobile phone, scan the code with WeChat and QQ, and the word "Hello World" will appear. Does it evoke your memory of learning Python for the first time?

It was just a small test, let's take an advanced step and save the generated QR code locally.

import qrcode

def second_demo():
    text = 'Python专栏'
    img = qrcode.make(text)
    # 需要传一个参数 文件名
    img.save('qr.png')
    img.show()

insert image description here

Everyone should be familiar with the two-dimensional code of my public account. The above steps are all pure two-dimensional codes, which are not in line with our temperament. Next I'm going to use the qrcode library to generate a QR code with an embedded image.

from PIL import Image
import qrcode

def create_icon_qrcode():
    qr = qrcode.QRCode(
        # 二维码size尺寸大小。官方称为version
        version=1,
        # 二维码错误处理级别,有四种方式,稍后给出解释
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        # 二维码图片的大小
        box_size=10,
        # 二维码白色边框的大小
        border=2
    )

    # 添加数据
    qr.add_data('小可爱你好,我是波多野结衣老湿')
    # 填充数据
    qr.make(fit=True)
    # 生成二维码图片        指定填充颜色        指定背景颜色
    img = qr.make_image(fill_color='grey',back_color='white')

    # 得到生成的二维码图片的宽,高
    img_w,img_h = img.size

    # 添加图片到二维码中
    # 使用pillow的Image打开图片
    icon = Image.open('girl.jpg')

    # 设置icon的大小,为二维码图片大小的6分之一
    factor = 3
    size_w = img_w // factor
    size_h = img_h // factor

    # 得到icon图片的大小
    icon_w,icon_h = icon.size

    # 只有当我们icon图片的大小超过了二维码图片的3分之一的时候,才对icon图片大小重新定义大小。
    if icon_w > size_w:
        icon_w = size_w
    if icon_h > size_h:
        icon_h = size_h

    # 重新设置icon的尺寸
    icon = icon.resize((icon_w,icon_h),Image.ANTIALIAS)
    # 得到在二维码中显示的位置,坐标。
    w =  (img_w - icon_w) // 2
    h =  (img_h - icon_h) // 2

    img.paste(icon,(w,h),mask=None)
    img.save('girl.png')

Let's talk about the version parameter and the error_correction parameter:

  • version: is the size of the QR code image, officially called version. When the version is 1, the QR code is a square composed of 2121, if the version is 2, it is 2525, and if the version is 3, it is 2929. The maximum is 40. So the maximum size is (40 - 1) * 4 + 21 = 177. That is 177177 squares.
  • error_correction: Error correction level, the higher the level, the stronger the error correction ability. This is why our QR code is a little incomplete, and the information can be read correctly.

Error correction capacity

  • L level: 7% of characters can be corrected
  • Level M: 15% of characters can be corrected
  • Q level: 25% of characters can be corrected
  • H level: 30% of characters can be corrected

Through the above steps, a QR code filled with a gray background is generated, the most core middle part... Who is she?

insert image description here

github address: https://github.com/lincolnloop/python-qrcode

The above is the basic use of the qrcode library. Next, I will introduce the MyQr library. This library is quite powerful, powerful enough to use images as backgrounds for QR codes, or even dynamic images.

Generate QR code using MyQr module

import os
from MyQR import myqr

def myqr_demo():
    # 注意,这里的字符串不能出现中文,只能以下这些
    # supported_chars = r"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ··,.:;+-*/\~!@#$%^&`'=<>[]()?_{}|"
    words = 'hello world'
    # 调用myqr.run方法,就能够生成图片了。返回三个值,二维码的version,纠错级别,二维码的完整路径
    version, level, qr_name = myqr.run(
        # 存放的数据
        words=words,
        # 二维码size
        version=10,
        # 选取的背景图片
        picture='girl.jpg',
        # 是否为彩色。如果为False,那么就是黑白的
        colorized=True,
        # 保存到本地的名字
        save_name='girl_img.png',
        # 保存二维码的目录,这里就是当前目录。默认就是这个
        save_dir=os.getcwd()
    )
    print(version,level,qr_name)

By executing the above code, we can generate a QR code with our picture as the background.

insert image description here

If you need to use the dynamic image as the background image, it is similar to the normal background image, you only need to write the file name of the background image, and then when saving the image, change the suffix of the QR code to gif.

github address: https://github.com/sylnsfar/qrcode

Here is a brief comparison of the two libraries.

  • qrcode supports Chinese data, while myqr does not support Chinese and other characters.
  • qrcode cannot set the background image, but it can place the image in the middle of the QR code.
  • myqr can set the background to a picture, and allows dynamic pictures.

Use zxing library to parse QR code

Above we only talked about how to generate a QR code image. Next, we will introduce how to parse the information in the QR code.

import zxing

def parse_qrcode(filename):
    reader = zxing.BarCodeReader()
    barcode = reader.decode(filename)
    print(barcode.parsed)

In just a few lines of code, complex and simple QR codes can be parsed and detailed data can be obtained.

**Note:** If the data in the QR code contains Chinese, such an error should be reported. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 0: invalid start byte At this time, you only need to modify the source code of this library.

The modification location is at line 81 in the __init__.pyfile .

Oh I see

raw = raw[:-1].decode()
parsed = parsed[:-1].decode()
return cls(format, type, raw, parsed, points)

It needs to be modified as follows

raw = raw[:-1].decode(encoding='gbk')
parsed = parsed[:-1].decode(encoding='gbk')
return cls(format, type, raw, parsed, points)

This way you can't go wrong.

In this way, we successfully parsed the QR code.

The full code of this article has been uploaded to Github: https://github.com/MiracleYoung/You-are-Pythonista/tree/master/PythonExercise/App/QRcode

For more fun and interesting Python content, pay attention to the public account " Python Column "

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324129243&siteId=291194637