1

- 我正在使用 python 将测试数据加载到我的 SQL Server 数据库中,并且能够成功获取图像并将它们分解为字节并将它们存储在数据库中,但是当尝试取回字节并将其解码以将其保存为一种新的文件类型,我得到的只是一个空白图像文件。不知道我在这里做错了什么......

- 我已经尝试使用其他教程和类似问题中的 base64 进行多次迭代,但似乎找不到可以解决我的问题的方法。

SQLCommand = ("SELECT Photo FROM Validation")


cursor.execute(SQLCommand)
data = cursor.fetchone()[0]




image_64_decode = base64.decodebytes(data)
image_result = open('booking.png', 'wb')
image_result.write(image_64_decode)
image_result.close()


connection.close()

The expected result is that I should be able to fetch the bytes from the database which the database column is varbinary(max) the equivalent of bytes in python. once the bytes are fetched using the script in python it should save a file as booking.png which should replicate the image i stored in the database.

When i run the script i don't get an error, and in fact it saves a file, but the file is empty containing 1kb and does not reproduce the image. Not sure where i am going wrong, but it seems like it's not properly fetching the bytes.
4

2 回答 2

1

确实不需要 base64 编码。如果您使用pyodbc而不是 pypyodbc 那么它很简单

# test data
photo_path = r'C:\Users\Public\Pictures' + '\\'
email = 'bob@example.com'

# test environment
cursor.execute("""\
CREATE TABLE #validation (
    email nvarchar(255) PRIMARY KEY, 
    photo varbinary(max))
""")

# save binary file
with open(photo_path + 'generic_man.jpg', 'rb') as photo_file:
    photo_bytes = photo_file.read()
cursor.execute("INSERT INTO #validation (email, photo) VALUES (?, ?)", email, photo_bytes)
print(f'{len(photo_bytes)}-byte file written for {email}')
# 5632-byte file written for bob@example.com

# retrieve binary data and save as new file
retrieved_bytes = cursor.execute("SELECT photo FROM #validation WHERE email = ?", email).fetchval()
with open(photo_path + 'new.jpg', 'wb') as new_jpg:
    new_jpg.write(retrieved_bytes)
print(f'{len(retrieved_bytes)} bytes retrieved and written to new file')
# 5632 bytes retrieved and written to new file
于 2019-07-09T17:51:20.533 回答
1

我能够让我的代码正常工作,并且可以成功地将图像转换为字节,将其存储在 sql server 数据库中,并通过获取字节并复制图像来检索它。

只有一个问题——这只有在我对存储图像字节的列使用 nvarchar(max) 数据类型时才有效。我在使用 varbinary(max) 或解决错误时遇到错误,它实际上并没有抓取并正确转换它 - 关于我可能做错的任何指导,因为我觉得它很小。下面更新的代码是我正在使用的 nvarchar(max) 正在做的事情。

import pypyodbc
import base64
from base64 import * 

connection = pypyodbc.connect('Driver=SQL Server;'
                            'Server=DESKTOP-MSSQLSERVER;'
                            'Database=Test;'
                            'Trusted_Connection=yes;'
                            )

cursor = connection.cursor()

a = 'bob@bob.com'
b = 'mack jones'
filename = 'bookingsuccessful.PNG'


image = open(filename, 'rb')
image_read = image.read()
image_64_encode = base64.encodebytes(image_read)


image.close()

SQLCommand = ("INSERT INTO Validation(email, myname, photo) VALUES(?,?,?)")
Values = [a,b,image_64_encode]
cursor.execute(SQLCommand, Values)
connection.commit()

SQLCommand = ("SELECT Photo FROM validation")
cursor.execute(SQLCommand)
data = cursor.fetchone()[0]
data = bytes(data.strip("\n"), 'utf-8')

image_64_decode = base64.decodebytes(data)
image_result = open('testfile.gif', 'wb')
image_result.write(image_64_decode)
image_result.close()

connection.close()
于 2019-07-08T06:36:10.780 回答