sqlserver base64转图片
时间: 2023-12-01 10:42:14 浏览: 111
Base64转图片
5星 · 资源好评率100%
以下是将BASE64加密的图片保存到SQL Server数据库中,并将其取出生成图片的完整示例代码:
```python
import pyodbc
import base64
from PIL import Image
from io import BytesIO
# 连接数据库
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=server_name;DATABASE=db_name;UID=user_id;PWD=password')
# 读取图片并进行BASE64编码
with open("image.jpg", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
# 将编码后的字符串插入到数据库中
cursor = conn.cursor()
cursor.execute("INSERT INTO image_table (image_data) VALUES (?)", encoded_string)
conn.commit()
# 从数据库中读取数据并解码
cursor.execute("SELECT image_data FROM image_table WHERE id = ?", 1)
row = cursor.fetchone()
encoded_string = row[0]
decoded_image = base64.b64decode(encoded_string)
# 将解码后的数据转换为图像并保存
image = Image.open(BytesIO(decoded_image))
image.save("decoded_image.jpg")
```
阅读全文