zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    月半小夜曲下的畅想--DOCTYPE模式
    css模块化思想(一)--------命名是个技术活
    聊聊css盒子模型
    【随笔】借鉴 & KPI式设计
    【转载】社交的蒸发冷却效应
    【随笔】写在闪电孵化器分享会之后
    【随笔】微信删除加载动画
    【随笔】微信支付有感 续
    【转载】如何把产品做简单
    【随笔】写在2014年的第一天
  • 原文地址:https://www.cnblogs.com/moonciki/p/15728347.html
Copyright © 2011-2022 走看看