Python生成二维码, Python生成SVG,如何在Python中创建QR代码图像或SVG, How to create a QR Code image or SVG in Python
快速响应(QR)代码是一种二维象形代码,由于其快速可读性和相对大的存储容量而被使用。代码由在白色背景上以正方形图案排列的黑色模块组成。如果您正在使用Python并且需要快速创建QR代码,我们将向您展示如何使用qrcode库在几秒钟内实现此目的。
1.安装所需的库
您需要在Python中添加的第一个库是Pillow。Python成像库,也称为PIL以及新版本的Pillow(在称为Pillow的新版本中)是Python编程语言的免费库,它增加了对打开,操作和保存许多不同图像文件格式的支持。它适用于Windows,Mac OS X和Linux。要创建QR代码,我们将使用依赖于Pillow的qrcode库
您可以在终端中安装此模块执行以下命令:
# REM Required to work with images pip install Pillow
完成Pillow安装后,您可以继续安装QR生成器库:
# REM install library to generate QR Codes pip install qrcode
否则,在没有Pillow的情况下,在使用QR代码库创建图像期间,您会收到消息错误“ ImportError:No module named Image ”。有关Pillow或qrcode的更多信息,请访问他们的主页。
2.将QR码创建为图像
您需要编写以创建QR代码的代码非常易于理解且非常简单。首先导入qrcode库并使用它的QRCode方法,然后根据需要提供参数
# Import QR Code library import qrcode # Create qr code instance qr = qrcode.QRCode( version = 1, error_correction = qrcode.constants.ERROR_CORRECT_H, box_size = 10, border = 4, ) # The data that you want to store data = "The Data that you need to store in the QR Code" # Add data qr.add_data(data) qr.make(fit=True) # Create an image from the QR Code instance img = qr.make_image() # Save it somewhere, change the extension as needed: # img.save("image.png") # img.save("image.bmp") # img.save("image.jpeg") img.save("image.jpg")
错误修正
QR码具有纠错功能,可在代码损坏或脏污时恢复数据。此库提供四个错误更正级别,它们存储在 qrcode.constants
对象中:
ERROR_CORRECT_L
:可以纠正大约7%或更少的错误。ERROR_CORRECT_M
:(默认)可以纠正大约15%或更少的错误。ERROR_CORRECT_Q
:可以纠正大约25%或更少的错误。ERROR_CORRECT_H
:可以纠正大约30%或更少的错误。
error_correction
在创建QR码期间,它们应作为财产的价值提供 。
QR码大小
您可以使用box_size
属性更改生成的QR代码的大小。
3.将QRCode创建为SVG
如果您愿意生成QRCode的SVG文件而不是图像,那么您还需要安装lxml库,因为旧xml.etree.ElementTree
版本不能用于创建SVG图像。lxml是一个XML工具包,是C库libxml2和libxslt的Pythonic绑定。它的独特之处在于它将这些库的速度和XML特性完整性与本机Python API的简单性相结合,大多数兼容但优于众所周知的ElementTree API。
要使用pip安装此模块,请在终端中运行以下命令:
pip install lxml
安装后,您将能够为将生成的SVG文件生成ElementTree。SVG的生成方法可以根据您的需要而不同,库提供3种类型的SVG,即SVG图像,使用片段或路径:
import qrcode import qrcode.image.svg # define a method to choose which factory metho to use # possible values 'basic' 'fragment' 'path' method = "basic" data = "Some text that you want to store in the qrcode" if method == 'basic': # Simple factory, just a set of rects. factory = qrcode.image.svg.SvgImage elif method == 'fragment': # Fragment factory (also just a set of rects) factory = qrcode.image.svg.SvgFragmentImage elif method == 'path': # Combined path factory, fixes white space that may occur when zooming factory = qrcode.image.svg.SvgPathImage # Set data to qrcode img = qrcode.make(data, image_factory = factory) # Save svg file somewhere img.save("qrcode.svg")
本文:Python生成二维码, Python生成SVG,如何在Python中创建QR代码图像或SVG, How to create a QR Code image or SVG in Python