Prepare the Environmentpython generates two-dimensional code that relies on packages QRCode and PIL (the essence of a QR code is a URL.) )Python3 Installing Pil:pip install PILpython2 installing Pil:pip Install Pillow
a method of generating two-dimensional code1. The simplest example of generating a QR code for a URL is as follows:Import QRCodeImg=qrcode.make ("www.zhuanzhuan.com")Img.save ("./test.png") 2. You can change the style of the generated QR code by qrcode Some of the configuration items, such as width, size, tolerance coefficientQr=qrcode. QRCode (version=2,error_correction=qrcode.constants.error_correct_l,Box_size=8,border=2 )3. You can paste a local image on a QR code image (limit the size of the image)The code is as follows:Import QRCodeFrom PIL import Image url= "www.zhuanzhuan.com"Qr=qrcode. QRCode (version=2,error_correction=qrcode.constants.error_correct_l,Box_size=8,border=2 )qr.add_data (url)Qr.make (fit=true)img=qr.make_image ()Img=img.convert ("RGBA")Icon=image.open ("./logo.png")img_w,img_h=img.sizefactor=4size_w=int (img_w/factor)size_h=int (img_h/factor) icon_w,icon_h=icon.sizeif Icon_w>size_w:Icon_w=size_wif Icon_h>size_h:Icon_h=size_hicon=icon.resize ((icon_w,icon_h), Image.antialias) W=int ((img_w-icon_w)/2)H=int ((img_h-icon_h)/2)img.paste (icon, (w,h), icon) img.save ("./test.png") Note:1. Add the image must be a local picture, with the network image can not write this2. The pasted image must be in the same format as the QR code, all PNG
problems encountered:1. Two-dimensional code add image this step, error: Valueerror:bad transparency Maskcause: It's a python pil merge picture error, but my two images are PNG, and then according to the online search scheme to convert the local image to paste, re-converted to PNG format, resolved the problemOnline conversion Address:http://apps3.bdimg.com/store/static/kvt/431a127b816a83768c98972cd5c6a06d.swf/http apps3.bdimg.com/store/static/kvt/431a127b816a83768c98972cd5c6a06d.swf 2.python2+mac and Python2+ubuntu system, PIL not installed, using QRCode to generate two-dimensional code times error: Ioerror:encoder Zip not availableWorkaround:1. Uninstall the PIL first, then reinstall the Pillowpip Uninstall PILpip Install pillowsome of the installation of Pillow will also report the problem of missing things, there may be lack of the following, direct installation is generally solved
apt-get install libjpeg62 libjpeg62-dev zlib1g-dev libfreetype6 libfreetype6-deva QR code with a picture is attached below:
Python transforms URLs into QR codes