版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
简介:
二维码简称 QR Code(Quick Response Code),学名为快速响应矩阵码,是二维条码的一种,由日本的 Denso Wave 公司于1994 年发明。现随着智能手机的普及,已广泛应用于平常生活中,例如商品信息查询、社交好友互动、网络地址访问等等。qrcode模块是Github上的一个开源项目,提供了生成二维码的接口。qrcode默认使用PIL库用于生成图像。由于生成 qrcode 图片需要依赖 Python 的图像库,所以需要先安装 Python 图像库 PIL(Python Imaging Library)。
项目地址: https://github.com/sylnsfar/qrcode
步骤:
1、安装qrcode和pillow
pip install qrcode pillow
2、安装完成后直接使用,示例如下:
import qrcode
img=qrcode.make("https://me.csdn.net/PY0312")
with open("test.png","wb") as f:
img.save(f)
在 python 环境下运行它即可生成一个二维码
3、基于 django 实现方法
a. 在 views.py 中添加以下代码:
from django.http import HttpResponse
import qrcode
from django.utils.six import BytesIO
def makeqrcode(request,data):
url = HOST+data
img = qrcode.make(url) # 传入网址计算出二维码图片字节数据
buf = BytesIO() # 创建一个BytesIO临时保存生成图片数据
img.save(buf) # 将图片字节数据放到BytesIO临时保存
image_stream = buf.getvalue() # 在BytesIO临时保存拿出数据
response = HttpResponse(image_stream, content_type="image/jpg") # 将二维码数据返回到页面
return response
b. 在 url.py 中添加以下代码:
urlpatterns = [
......
url(r'qrcode/(.+)$', views.makeqrcode,name='qrcode')
......
]
c. 在模板中使用:
<img src="{% url 'qrcode' request.path %}" width="120px" height="120px;">