将图片保存到MySQL数据库通常有两种方法:一种是将图片转换为二进制数据(BLOB)并直接存储在数据库中;另一种是将图片存储在文件系统中,并在数据库中保存图片的路径。下面分别介绍这两种方法。
TINYBLOB
:最大 255 字节。BLOB
:最大 65,535 字节。MEDIUMBLOB
:最大 16,777,215 字节。LONGBLOB
:最大 4,294,967,295 字节。假设我们有一个表 images
,结构如下:
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
image BLOB
);
插入图片:
import mysql.connector
def save_image_to_db(image_path):
conn = mysql.connector.connect(user='your_user', password='your_password',
host='your_host', database='your_database')
cursor = conn.cursor()
with open(image_path, 'rb') as file:
binary_data = file.read()
query = "INSERT INTO images (name, image) VALUES (%s, %s)"
cursor.execute(query, (image_path.split('/')[-1], binary_data))
conn.commit()
cursor.close()
conn.close()
save_image_to_db('path/to/your/image.jpg')
读取图片:
def get_image_from_db(image_id):
conn = mysql.connector.connect(user='your_user', password='your_password',
host='your_host', database='your_database')
cursor = conn.cursor(buffered=True)
query = "SELECT name, image FROM images WHERE id = %s"
cursor.execute(query, (image_id,))
result = cursor.fetchone()
if result:
name, image = result
with open(f'retrieved_{name}', 'wb') as file:
file.write(image)
cursor.close()
conn.close()
get_image_from_db(1)
VARCHAR
或 TEXT
)。假设我们有一个表 images
,结构如下:
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
path VARCHAR(255)
);
插入图片:
import os
import mysql.connector
def save_image_to_filesystem(image_path):
conn = mysql.connector.connect(user='your_user', password='your_password',
host='your_host', database='your_database')
cursor = conn.cursor()
new_path = f'uploads/{image_path.split("/")[-1]}'
os.rename(image_path, new_path)
query = "INSERT INTO images (name, path) VALUES (%s, %s)"
cursor.execute(query, (image_path.split('/')[-1], new_path))
conn.commit()
cursor.close()
conn.close()
save_image_to_filesystem('path/to/your/image.jpg')
读取图片:
def get_image_from_filesystem(image_id):
conn = mysql.connector.connect(user='your_user', password='your_password',
host='your_host', database='your_database')
cursor = conn.cursor(buffered=True)
query = "SELECT name, path FROM images WHERE id = %s"
cursor.execute(query, (image_id,))
result = cursor.fetchone()
if result:
name, path = result
print(f'Image can be accessed at: {path}')
cursor.close()
conn.close()
get_image_from_filesystem(1)
选择哪种方法取决于具体需求和应用场景。希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云