Look program all over the world, there is naturally there are code

Last played Sudoku ( next to the Friends of Sudoku will be cutting it? Python seconds stops at cutting alone understand it? ) Thing to ...... Pharaoh gas directly this time I took out the photos to see his reaction.

The chubby VIP code combination, see if he Which will lead to trouble.

That qualified as a programmer, how can you not know how to generate two-dimensional code, how to interpret, how to play it? Ado, let's play today in Python yards one person.

Demo environment

  • Operating System: windows10
  • python version: python 3.7
  • Code Editor: pycharm 2018.2
  • Use Module: zxing, myqr, qrcode
  • tips: the above modules are installed using pip, they rely on the module will be automatically installed, you will not believe it will Python to pip too strange.
pip install qrcode
pip install myqr
pip install zxing

Use qrcode module generates two-dimensional code

First, we generate a "Hello World".

import qrcode

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

Through the above steps to complete this classic entry, take out your cell phone, micro letter, QQ scan code, there will be "Hello World" words, is there brought back memories do you begin to learn Python.

Was just a small test chopper, we advanced to a, to save the generated two-dimensional code locally.

import qrcode

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

My public two-dimensional code number we should be very familiar with it, the above steps are generated purely two-dimensional code, does not comply with our temperament. Next, I want to use qrcode library to generate two-dimensional code with embedded pictures.

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')

Said here about the version parameters and error_correction parameters:

  • version: that is, two-dimensional code image size, officially known as version. version is to 1, the two-dimensional code is 2121 square composition, version 2 for the word is 2525, version 3 is 2929 words. The maximum is 40. So that the maximum size of (40 - 1) * 4 + 21 = 177. That is 177177 square.
  • error_correction: error correction level, the higher the level, the stronger error correction capability. This is why our two-dimensional code a little incomplete, it is possible to correctly read cause information.

Error correction capacity

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

Through the above steps, it generates a gray background fill of two-dimensional code, the core of most of the middle part ...... Who is she?

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

The above is the basic use qrcode library. Then tell us about MyQr library. The library is quite strong, strong enough to use as a background picture two-dimensional code, and even dynamic map.

Use MyQr module generates two-dimensional code

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)

Execute the code above, we can generate a two-dimensional code to our picture as a background.

If you need a dynamic map as background map, in fact, similar to normal background image, background only need to write the file name on the line, and then save the picture when the extension of the two-dimensional code can be changed to gif.

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

Here simply compare these two libraries it

  • qrcode support Chinese data, but does not support Chinese characters such myqr.
  • qrcode can not set the background image, but can picture in the middle of a two-dimensional code.
  • myqr may be set to the background image, and allows dynamic FIG.

Use zxing two-dimensional code parsing library

Above we just say how to generate a two-dimensional code images. Next introduce information on how to resolve the two-dimensional code.

import zxing

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

Just a few lines of code will be able to resolve the complex and simple two-dimensional code, and to obtain detailed data inside.

Note: If the data in the two-dimensional code that contains Chinese, you should report such a mistake. UnicodeDecodeError: 'utf-8' codec can not decode byte 0xc0 in position 0: invalid start byte this time only need to modify the source code of the library on the line.

Modifying the position zxing packet following __init__.pyline of code 81 of the document.

Oh I see

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

We need 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 will not go wrong.

In this way, we have successfully resolved a two-dimensional code.

本文全套代码已上传至Github:https://github.com/MiracleYoung/You-are-Pythonista/tree/master/PythonExercise/App/QRcode

更多好玩有趣的Python内容,关注公众号「Python专栏

Guess you like

Origin www.cnblogs.com/moonhmily/p/11375077.html