Creating QR Code With Google
So today I thought I would be neat to show how to quickly create QR codes using Google’s Chart Tools .
Google gives us a extremely easy way to create QR code by sending GET data request via URL: https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=nessy That is nice and easy, but I figured I would wrap this up in a small Python script just because:
#!/usr/bin/env python
from urllib2 import quote, urlopen, Request
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import sys
def create(width, heigth, data):
'''Builds a URL for Google to create us a QR code'''
# build and make URL request
google_chart = 'https://chart.googleapis.com'
url = '%s/chart?cht=qr&chs=%sx%s&chl=%s' % (google_chart, width, heigth, quote(data))
request = urlopen(url)
response = request.read()
# write QR code to file
f = open('qr.png', 'w')
f.write(response)
f.close
return 'Wrote qr.png..'
def read(qr_file):
'''Reads a QR code by URL'''
# post image to decode page
register_openers()
datagen, headers = multipart_encode({'f': open(qr_file)})
request = Request('http://zxing.org/w/decode', datagen, headers)
response = urlopen(request).read()
return response
if sys.argv[1] == 'create':
print create(300, 300, sys.argv[2])
if sys.argv[1] == 'read':
print read(sys.argv[2])
Basic usage works like so:
$ ./qr.py create "My name is Nessy, Hello"
Wrote qr.png..
Running the create option will write a file named qr.png to your current directory:
$ file qr.png
qr.png: PNG image, 300 x 300, 8-bit/color RGB, non-interlaced
And reading this QR code works just like this:
$ ./qr.py read qr.png
My name is Nessy, Hello