gpt4 book ai didi

python - 我如何将从数据库接收到的blob数据转换为python中的图像

转载 作者:行者123 更新时间:2023-12-01 07:01:17 27 4
gpt4 key购买 nike

我从数据库接收longblob数据。

我尝试将 blob 数据转换为图像并使用 cv2 读取图像。

所以我尝试将 blob 数据转换为 base64,如下面的代码,但失败了。

img = base64.decodebytes(img_str)

如何将 blob 转换为图像? cv2 包中是否有针对此问题的转换功能?

最佳答案

您不需要 cv2 将 blob 转换为图像,您需要将 blob/图像存储在磁盘上并显示它。这里是从 mysql blob 检索到磁盘文件的示例..

祝你好运!

引用的页面网址:URL

import mysql.connector
from mysql.connector import Error

def write_file(data, filename):
# Convert binary data to proper format and write it on Hard Disk
with open(filename, 'wb') as file:
file.write(data)

def readBLOB(emp_id, photo, bioData):
print("Reading BLOB data from python_employee table")

try:
connection = mysql.connector.connect(host='localhost',
database='python_db',
user='pynative',
password='pynative@#29')

cursor = connection.cursor()
sql_fetch_blob_query = """SELECT photo from python_employee where id = %s"""

cursor.execute(sql_fetch_blob_query, (emp_id,))
record = cursor.fetchall()
for row in record:
print("Id = ", row[0], )
print("Name = ", row[1])
image = row[2]
file = row[3]
print("Storing employee image and bio-data on disk \n")
write_file(image, photo)
write_file(file, bioData)

except mysql.connector.Error as error:
print("Failed to read BLOB data from MySQL table {}".format(error))

finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")

readBLOB(1, "D:\Python\Articles\my_SQL\query_output\eric_photo.png",
"D:\Python\Articles\my_SQL\query_output\eric_bioData.txt")
readBLOB(2, "D:\Python\Articles\my_SQL\query_output\scott_photo.png",
"D:\Python\Articles\my_SQL\query_output\scott_bioData.txt")

关于python - 我如何将从数据库接收到的blob数据转换为python中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58621031/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com