天天看點

Python将文本生成二維碼

Python将文本生成二維碼 Python生成帶Logo的二維碼

#coding:utf-8
'''
Python生成二維碼 v1.0
主要将文本生成二維碼圖檔
 
測試一:将文本生成白底黑字的二維碼圖檔
測試二:将文本生成帶logo的二維碼圖檔
 
'''
 
__author__ = 'Xue'
 
import qrcode
from PIL import Image
import os
 
#生成二維碼圖檔
def make_qr(str,save):
    qr=qrcode.QRCode(
        version=4,  #生成二維碼尺寸的大小 1-40  1:21*21(21+(n-1)*4)
        error_correction=qrcode.constants.ERROR_CORRECT_M, #L:7% M:15% Q:25% H:30%
        box_size=10, #每個格子的像素大小
        border=2, #邊框的格子寬度大小
    )
    qr.add_data(str)
    qr.make(fit=True)
 
    img=qr.make_image()
    img.save(save)
 
 
#生成帶logo的二維碼圖檔
def make_logo_qr(str,logo,save):
    #參數配置
    qr=qrcode.QRCode(
        version=4,
        error_correction=qrcode.constants.ERROR_CORRECT_Q,
        box_size=8,
        border=2
    )
    #添加轉換内容
    qr.add_data(str)
    #
    qr.make(fit=True)
    #生成二維碼
    img=qr.make_image()
    #
    img=img.convert("RGBA")
 
    #添加logo
    if logo and os.path.exists(logo):
        icon=Image.open(logo)
        #擷取二維碼圖檔的大小
        img_w,img_h=img.size
 
        factor=4
        size_w=int(img_w/factor)
        size_h=int(img_h/factor)
 
        #logo圖檔的大小不能超過二維碼圖檔的1/4
        icon_w,icon_h=icon.size
        if icon_w>size_w:
            icon_w=size_w
        if icon_h>size_h:
            icon_h=size_h
        icon=icon.resize((icon_w,icon_h),Image.ANTIALIAS)
        #詳見:http://pillow.readthedocs.org/handbook/tutorial.html
 
        #計算logo在二維碼圖中的位置
        w=int((img_w-icon_w)/2)
        h=int((img_h-icon_h)/2)
        icon=icon.convert("RGBA")
        img.paste(icon,(w,h),icon)
        #詳見:http://pillow.readthedocs.org/reference/Image.html#PIL.Image.Image.paste
 
    #儲存處理後圖檔
    img.save(save)
 
 
if __name__=='__main__':
    save_path='theqrcode.png' #生成後的儲存檔案
    logo='logo.jpg'  #logo圖檔
 
    str=raw_input('請輸入要生成二維碼的文本内容:')
 
    #make_qr(str)
 
    make_logo_qr(str,logo,save_path)      
Python将文本生成二維碼

作者:酷小孩

出處:http://www.cnblogs.com/babycool/

本文首發部落格園,版權歸作者跟部落格園共有。

轉載必須保留本段聲明,并在頁面顯著位置給出本文連結,否則保留追究法律責任的權利。