class - qrcode

最後更新: 2021-03-03

 


Install

 

# Centos package (epel)

python-qrcode

# Debian

pip install qrcode

pip install pillow

# Window:

easy_install.exe qrcode
easy_install.exe pillow

* QR library 依賴 image libraries, Python Imaging Library (PIL)

  (recommended to use the pillow fork (Python Imaging Library (Fork)) )

 


Usgae

 

# 建立 QR Code Easy Version

#!/usr/bin/env python
import qrcode
img = qrcode.make('Some data here')
img.save('qr.png')       # Image type 與 extension 無關

# 建立 QR Code Advanced Usage

#!/usr/bin/env python
import qrcode

# 建立 qrcode object
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)

qr.add_data('Some data')

qr.make(fit=True)

img = qr.make_image()

Parameter:

error_correction

  • ERROR_CORRECT_L         7%
  • ERROR_CORRECT_M        15% (Default)
  • ERROR_CORRECT_Q        25%
  • ERROR_CORRECT_H        30%

box_size            how many pixels each "box" of the QR code

border                 # default is 4

version 與 fit

value from 1 ~ 40, that controls the size of the QR Code

version 1 => 21x21 matrix

version=NONE,fit=True

making the qr code to determine size automatically

讀 QR Code (decode)

apt-get install python-qrtools

/usr/bin/env python

import qrtools

qr = qrtools.QR()
qr.decode("qr.png")
print qr.data

 


Full Example

 

#!/usr/bin/env python

import qrcode
from PIL import Image

link='http://datahunter.org'

qr = qrcode.QRCode(
    error_correction=qrcode.constants.ERROR_CORRECT_H,
)

qr.add_data(link)

qr.make(fit=True)

img = qr.make_image()

img.save("qr.png")

print "Done"

 


Troubleshoot

 

[1]

import qrcode
img = qrcode.make('Some data here')

# print type(img)
# <class 'qrcode.image.pil.PilImage'> 

myfile = file("qrcode.png",'wb')
myfile.write(img)
myfile.close()
print "Done"

會有 Error:

TypeError: must be convertible to a buffer, not PilImage

解決方法:

# 不用 file 寫檔案, 直接用 Class 的 save() 把圖片寫進去
img.save("qrcode.png")

原因:

因為 img 係 object 來, 不是 binary 資料

 


QR Code url syntax

 

http://example.com/

mailto:[email protected]

tel:1111111

 


DOC

 

https://pypi.python.org/pypi/qrcode

 

 

 

Creative Commons license icon Creative Commons license icon