批量处理图片转base64编码

# -*- coding:utf-8 -*-
"""
__project_ = 'ToBase64'
__file_name__ = 'PicToBase64'
__author__ = 'xbxia'
__time__ = '2020/10/26 9:37'
__product_name = PyCharm

"""
import os
import re
import base64
from queue import Queue

times = 0

# 保存结果到txt
def save_parse_result(content):
    f = open('pic_base64_result.txt', 'a+', encoding='utf-8')
    f.write(content + '\n')
    f.close()

# 匹配图片模式入队列
def put_picfile_to_queue(filepath, q):
    global times
    files = os.listdir(filepath)
    pic_re_pattern = re.compile(r"^.*\.(?:png|jpg|bmp|gif|tif|jpeg)$")
    for fi in files:
        fi_d = os.path.join(filepath, fi)
        if not os.path.isdir(fi_d):
            if pic_re_pattern.match(fi.lower()):
                q.put(fi_d)
                times += 1
        else:
            pass


# 队列发请求
def run_post(q):
    while not q.empty():
        filepath = q.get()
        pic_to_base64(filepath)


#图片转base64
def pic_to_base64(file):
    with open(file, 'rb') as fp:  # 二进制方式打开图文件
        fpBase64 = base64.b64encode(fp.read())  # 读取文件内容,转换为base64编码
        content = '{}\n, base64:{}'.format(file, fpBase64)
        print(content)
        save_parse_result(content)



if __name__ == '__main__':

    filepath = r"F:\Data\NewDesktop\1"

    # 创建Queue对象
    file_queue = Queue()
    put_picfile_to_queue(filepath, file_queue)  # 图片队列

    run_post(file_queue)

 

posted @ 2020-10-29 16:08  ReluStarry  阅读(784)  评论(0编辑  收藏  举报