Python Base64字符转图片

一、需求来源

近期,我们正在做数据迁移的工作。现目前的需求现状是:需将数据库材料表中所有的用户材料数据下载下来,做备份和下一步工作使用,这个任务便落在了我的头上。
我的任务是将每位用户的六张材料图下载下来,存在每个人单独的文件夹中 。

二、解题思路

在解题之前,需阐明,材料数据是完整base64字符(转化后其实就是一张张图片),数据量太大了,每次打开表都要打开半天,转换之前需将“data:image/png;base64,”替换掉。

1.excel导入方式

最开始的想法是,将我所需要的字段和图片字段通过excel导出,我再通过Python读取excel表格,在转换数据,形成一张张图片。结果表明base64字符太长了,excel上面根本无法操作,所以过了一会儿就放弃了

2.数据库连接方式

而后想起可以直接通过连接数据库的方式,读取材料表数据,最后进行转化。
代码如下(示例):

import base64
import time
import uuid

import pymysql
import os

file_path = r'D:\LawyerAttachment'
# 如果不存在上面的文件夹,则创建。
if not os.path.exists(file_path):
    os.makedirs(file_path)
    print("文件夹创建成功")

# 输入你的数据库连接地址、账户和密码以及数据库名称
db = pymysql.connect(host="", user="", passwd="", database="", charset='utf8')
print(db)
# 使用cursor()方法获取操作游标
cursor = db.cursor()

print("开始连接数据库" + time.time())
sql = """SELECT * FROM sys_organization_20220426"""
print("数据库查询完毕" + time.time())
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
    results = cursor.fetchall()
    for row in results:
   	    # row[]就是数据库库中的字段名
        name = row[5] # 用户姓名
        one = row[7]  # 第一张
        two = row[8]  # 第二张
        three = row[9]  # 第三张
        four = row[10]  # 第四张
        five = row[11]  # 第五张
        six = row[12]  # 第六张
        # 创建姓名+时间文件夹
        worker_path = file_path + "\\{}".format(name + uuid.uuid4().hex)
        if not os.path.exists(worker_path):
            os.makedirs(worker_path)
            print(name + "的文件夹创建成功了")
        else:
            print(name + "的文件夹已存在")
        # one = one.replace(' ', '+')
        if (one == "" or one == None):
            print(name + "图片为空")
        else:
            img_data1 = base64.b64decode(one)
            with open(worker_path + r'\1.png', 'wb') as f:
                f.write(img_data1)

        if (two == "" or two == None):
            print(name + "图片为空")
        else:
            img_data2 = base64.b64decode(two)
            with open(worker_path + r'\2.png', 'wb') as f:
                f.write(img_data2)

        if (three == "" or three == None):
            print(name + "图片为空")
        else:
            img_data3 = base64.b64decode(three)
            with open(worker_path + r'\3.png', 'wb') as f:
                f.write(img_data3)

        if (four == "" or four == None):
            print(name + "图片为空")
        else:
            img_data4 = base64.b64decode(four)
            with open(worker_path + r'\4.png', 'wb') as f:
                f.write(img_data4)

        if (five == "" or five == None):
            print(name + "图片为空")
        else:
            img_data5 = base64.b64decode(five)
            with open(worker_path + r'\5.png', 'wb') as f:
                f.write(img_data5)

        if (six == "" or six == None):
            print(name + "图片为空")
        else:
            img_data6 = base64.b64decode(six)
            with open(worker_path + r'\6.png', 'wb') as f:
                f.write(img_data6)
except Exception as e:
    # Rollback in case there is any error
    print("查询错误:", e)
    db.rollback()
db.close()


总结

做完之后才想到其实也可以用java完成该任务的,只怪我当时一心想到用Python去了。整个过程就查询数据库非常耗费之间,base64编码转图片的时候几乎就是几秒钟就完成了。
大概方法就是这样。
新手小白,刚上路,有许多知识不清楚,有许多的不足之处,还望大家多多指点一下我,谢谢啦。

当你接收到一个通过Base64编码过的字符串表示的图片时,你需要将其解码回原始的二进制形式,并保存为图片文件。以下是详细步骤以及对应的Python代码示例来完成这一任务: ### 步骤说明 1. **导入所需库** 需要引入`base64`标准库来进行解码工作,同时如果想要显示或进一步处理这张图片的话还可以选择性地加载`PIL.Image`(来自Pillow包)或其他图像处理相关的库。 2. **准备Base64编码的字符串** 确保你已经有了代表一张图片Base64编码后的字符串。通常这样的字符串会以某种前缀开头(例如"data:image/png;base64,"),这是为了指明数据的内容类型及编码方式,但在实际操作中我们可以忽略这部分内容仅保留纯编码部分。 3. **去除Base64字符串中的非编码字符** 如果你的Base64字符串包含了前面提到的那种描述性的头部信息,则需要先把它们去掉,只留下真实的Base64编码部分。 4. **解码Base64字符串得到byte数组** 利用`base64.decodebytes()`或者`base64.b64decode()`函数可以将Base64编码换回原本的字节流(byte array)。 5. **创建并保存图片文件** 把上述获得的字节数组写入一个新的文件即生成了相应的图片文件。 6. (可选)使用PIL展示图片 若你想立即查看结果而不必手动打开图片文件夹找到新建立好的文件,那么利用Pillow库可以帮助你在程序内部显示出该图片预览窗口。 ### 示例代码 这里给出一段简单的Python脚本来演示以上流程: ```python import base64 from PIL import Image from io import BytesIO def base64_to_image(base64_str, output_path=None): """ Convert a base64 string to an image file. :param base64_str: The input base64 encoded string representing the image content without prefix like 'data:image/jpeg;base64,'. :param output_path: Path where you want to save the decoded image. If None, it won't be saved but returned as PIL Image object instead. :return: A Pillow Image instance if no path provided for saving; otherwise returns nothing. """ # Remove any data URI scheme prefixes and decode clean_base64 = ','.join(base64_str.split(',')[1:]) if ',' in base64_str else base64_str img_bytes = base64.b64decode(clean_base64) # Create an IO stream from bytes byte_stream = BytesIO(img_bytes) # Open image using PIL/Pillow library img = Image.open(byte_stream).convert("RGB") if output_path: img.save(output_path) else: return img if __name__ == "__main__": # Example usage - replace this with your actual Base64-encoded string example_base64_jpg = "YOUR_BASE_64_ENCODED_IMAGE_STRING_HERE" result_img = base64_to_image(example_base64_jpg) result_img.show() # Display the resulting image directly # Or alternatively specify a filepath to write out the image there # base64_to_image(example_base64_jpg, "./output.jpg") ``` 这段脚本展示了怎样接收一个Base64编码过且可能含有MIME类型的头信息的字符串输入,对其进行清理和解码之后最终恢复出原图,并可以选择是否直接存储下来或是即时显示出来供开发者确认效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值