python:文件轉二維碼(拆分轉換)


文件轉二維碼時,考慮到二維碼存儲內容有限,可以使用拆分成多個二維碼的的方案

 

方案詳細流程

1. 將原始文件使用最高壓縮率bz2 進行壓縮

2. 將壓縮文件轉成base64

3. 將base64 進行拆分,拆分內容中拼上序號

4. 將上方base64及序號內容轉二維碼

5. 存儲二維碼

話不多數,直接上代碼

  1 import base64
  2 import os
  3 
  4 import qrcode
  5 from PIL import Image, ImageDraw, ImageFont
  6 from pyzbar import pyzbar
  7 
  8 # 文件轉 base64
  9 def fileToBase64(filePath):
 10     base64Text = ''
 11     with open(filePath, 'rb') as f1:
 12 
 13         base64Data = base64.b64encode(f1.read())  # base64類型
 14         #  b'JVBERi0xLjUNCiXi48
 15         base64Text = base64Data.decode('utf-8')  # str
 16         # JVBERi0xLjUNCiXi48/
 17 
 18     return base64Text
 19 
 20 def base64ToFile(base64Data, filePath):
 21 
 22     with open(filePath, 'wb') as f1:
 23 
 24         fileBytes = base64.b64decode(base64Data)
 25 
 26         f1.write(fileBytes)
 27 
 28     print("qrcode_files_decode_done ... ")
 29 
 30 # 寫文件文本內容
 31 def writeFileText(filePath, text):
 32     with open(filePath, 'wb') as f1:
 33 
 34         f1.write(text.encode('utf-8'))
 35 
 36 # 編碼成二維碼
 37 def writeQrcode(outPath, dataText):
 38     imgName = os.path.basename(outPath)
 39 
 40     qrImg = qrcode.make(dataText)
 41     width, height = qrImg.size
 42     newImage = Image.new(mode='RGB', size=(width, height + 50), color=(200, 200, 255))
 43     newImage.paste(qrImg, (0, 50, width, height + 50))
 44     draw = ImageDraw.Draw(newImage)
 45     font = ImageFont.truetype("arial.ttf", 30)
 46     draw.text((width / 2, 5), imgName, (255, 0, 0), font)
 47 
 48     newImage.save(outPath)
 49 
 50     '''
 51     qr=qrcode.QRCode(
 52         version=40,  #生成二維碼尺寸的大小 1-40  1:21*21(21+(n-1)*4)
 53         error_correction=qrcode.constants.ERROR_CORRECT_M, #L:7% M:15% Q:25% H:30%
 54         box_size=10, #每個格子的像素大小
 55         border=10, #邊框的格子寬度大小
 56     )
 57     qr.add_data(dataText)
 58     #qr.make(fit=True)
 59 
 60     img=qr.make_image()
 61     #img.show()
 62     img.save(outPath)
 63     '''
 64 
 65 
 66 # 解碼成原始文件
 67 def readQrcode(qrcodePath):
 68     qrcodeText = ""
 69     qucodeImg = Image.open(qrcodePath)
 70 
 71     pzDecodeImg = pyzbar.decode(qucodeImg)
 72 
 73     for barcode in pzDecodeImg:
 74         qrcodeText = barcode.data.decode("utf-8")##二維碼的data信息
 75         # print(qrcodeText)
 76         barcoderect=barcode.rect##二維碼在圖片中的像素坐標位置
 77         qr_size=list(barcoderect)
 78 
 79     # 拿到內容
 80     # print(qrcodeText)
 81     return qrcodeText
 82 
 83 
 84 # 文件拆分並轉二維碼
 85 def fileToQrcodes(qrcodeFolder, base64Str, textLength) -> object:
 86     index = 0
 87     startIndex = 0
 88     endIndex = 0
 89 
 90     while (endIndex < len(base64Str)):
 91         startIndex = index * textLength
 92         endIndex = startIndex + textLength
 93 
 94         if endIndex > len(base64Str):
 95             endIndex = len(base64Str)
 96 
 97         partText = base64Str[startIndex : endIndex]
 98 
 99         qrFile = qrcodeFolder + ('%d' % index) + ".jpg"
100         writeQrcode(qrFile, "%d|%s" % (index, partText))
101 
102         print("%d | %s" % (index, partText))
103 
104         index = index + 1
105 
106 def getBase64Array(root, files):
107     base64Array = [""] * len(files)
108 
109     # 遍歷文件
110     for oneQr in files:
111         oneQrPath = os.path.join(root, oneQr)
112         qrText = readQrcode(oneQrPath);
113         splitIndex = qrText.find('|');
114         qrIndex = int(qrText[0 : splitIndex])
115         partBase64 = qrText[splitIndex + 1:]
116 
117         base64Array[qrIndex] = partBase64
118         print(qrText)
119 
120     indexTmp = 0
121     for oneText in base64Array:
122         if oneText.strip() == '' :
123             # print("二維碼對應base64段缺失 :%d" % indexTmp)
124             raise Exception(print("二維碼解碼異常 :對應base64段缺失 :%d" % indexTmp))
125         indexTmp = indexTmp + 1
126 
127     return base64Array
128 
129 # 多個二維碼轉成文件
130 def qrcodesToFile(qrcodeFolder, filePath):
131 
132     for root, dirs, files in os.walk(qrcodeFolder):
133         print(root) #當前目錄路徑
134         print(dirs) #當前路徑下所有子目錄
135         print(files) #當前路徑下所有非目錄子文件
136 
137         base64Array = getBase64Array(root, files)
138 
139         fullBase64Data = ''.join(base64Array)
140 
141         writeFileText("D:/source-files/test/qr/postman-api.base64-2", fullBase64Data)
142 
143         base64ToFile(fullBase64Data, filePath)
144 
145         print(base64Array)
146 
147     print("end ing ")
148 
149 if __name__ == "__main__":
150 
151     #原始文件
152     filePath = "D:/source-files/test/qr/postman-api.json.bz2"
153     # 二維碼輸出文件夾
154     qrcodeFolder = "D:/source-files/test/qr/img/"
155     # 二維碼長度拆分,太長攝像頭有可能無法識別
156     textLength = 300
157 
158     # 初始化文件夾
159     if not os.path.exists(qrcodeFolder):
160         os.makedirs(qrcodeFolder)
161 
162     base64Str = fileToBase64(filePath)
163 
164     print(base64Str)
165 
166     #base64Str = "0123456789-=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()_+:;,./?|<>"
167 
168     fileToQrcodes(qrcodeFolder, base64Str, textLength)
169 
170     #### 解析二維碼
171     decodeFilePath = "D:/source-files/test/qr/decode/"
172     # 初始化文件夾
173     if not os.path.exists(decodeFilePath):
174         os.makedirs(decodeFilePath)
175 
176     qrcodesToFile(qrcodeFolder, decodeFilePath + "decode.json.bz2")
177 
178     # 測試
179     outFile = "D:/source-files/test/qr/postman-api.base64"
180     writeFileText(outFile, base64Str)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM