图片怎么写入与读出数据库
时间: 2023-06-10 09:05:38 浏览: 70
要将图片写入数据库,你需要将其转换为二进制格式并将其存储在数据库的BLOB字段中。可以使用Python的Pillow库来打开、读取和转换图像文件。以下是将一张名为“image.png”的图片写入数据库的示例代码:
```python
import mysql.connector
from mysql.connector import Error
from PIL import Image
# 读取要写入的图片
img = Image.open('image.png')
# 将图片转换为二进制格式
with open("image.bin", "wb") as f:
f.write(img.tobytes())
# 连接数据库
try:
conn = mysql.connector.connect(host='localhost',
database='my_database',
user='my_username',
password='my_password')
if conn.is_connected():
print('Connected to MySQL database')
# 将二进制数据写入数据库
cursor = conn.cursor()
sql_insert_blob_query = """ INSERT INTO my_table
(id, image_data) VALUES (%s,%s)"""
with open("image.bin", "rb") as f:
image_blob = f.read()
# 执行 SQL 语句并提交到数据库
cursor.execute(sql_insert_blob_query, (1, image_blob))
conn.commit()
print("Image and file inserted successfully as a BLOB into MySQL table")
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
```
要从数据库中读取图像,可以使用以下代码:
```python
# 连接数据库
try:
conn = mysql.connector.connect(host='localhost',
database='my_database',
user='my_username',
password='my_password')
if conn.is_connected():
print('Connected to MySQL database')
# 从数据库中读取二进制数据
cursor = conn.cursor()
sql_fetch_blob_query = """SELECT image_data FROM my_table WHERE id = %s"""
cursor.execute(sql_fetch_blob_query, (1,))
record = cursor.fetchone()
# 将数据转换为图像文件并保存到磁盘上
with open("image_out.png", "wb") as f:
f.write(record[0])
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
```
这将从数据库中读取id为1的记录中的图像数据,并将其保存为名为“image_out.png”的文件。