在Flask应用中从MySQL数据库读取图片并返回给前端显示,通常有两种主要方法:直接返回二进制数据或返回Base64编码的图片。下面我将详细介绍这两种方法的实现。
这种方法效率较高,适合大图片传输。
假设你的MySQL表结构如下:
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
data LONGBLOB,
mime_type VARCHAR(50)
);
from flask import Flask, Response
import mysql.connector
app = Flask(__name__)
# MySQL配置
db_config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'your_database'
}
@app.route('/image/<int:image_id>')
def get_image(image_id):
try:
# 连接数据库
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor()
# 查询图片数据
cursor.execute("SELECT data, mime_type FROM images WHERE id = %s", (image_id,))
image_data, mime_type = cursor.fetchone()
# 关闭连接
cursor.close()
conn.close()
# 返回图片响应
return Response(image_data, mimetype=mime_type)
except Exception as e:
return str(e), 500
if __name__ == '__main__':
app.run(debug=True)
<img src="/image/1" alt="Database Image">
这种方法适合小图片或需要内联显示的情况。
from flask import Flask, jsonify
import mysql.connector
import base64
app = Flask(__name__)
# MySQL配置
db_config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'your_database'
}
@app.route('/image_base64/<int:image_id>')
def get_image_base64(image_id):
try:
# 连接数据库
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor()
# 查询图片数据
cursor.execute("SELECT data, mime_type FROM images WHERE id = %s", (image_id,))
image_data, mime_type = cursor.fetchone()
# 关闭连接
cursor.close()
conn.close()
# 转换为Base64
image_base64 = base64.b64encode(image_data).decode('utf-8')
# 返回JSON响应
return jsonify({
'mime_type': mime_type,
'image_data': image_base64
})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
<img id="dbImage" alt="Database Image">
<script>
fetch('/image_base64/1')
.then(response => response.json())
.then(data => {
document.getElementById('dbImage').src =
`data:${data.mime_type};base64,${data.image_data}`;
});
</script>
如果你还需要知道如何将图片存入数据库,这里是一个示例:
from flask import Flask, request
import mysql.connector
app = Flask(__name__)
# MySQL配置
db_config = {
'host': 'localhost',
'user': 'your_username',
'password': 'your_password',
'database': 'your_database'
}
@app.route('/upload', methods=['POST'])
def upload_image():
if 'file' not in request.files:
return 'No file uploaded', 400
file = request.files['file']
if file.filename == '':
return 'No selected file', 400
try:
# 读取文件数据
image_data = file.read()
mime_type = file.mimetype
# 连接数据库
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor()
# 插入图片数据
cursor.execute(
"INSERT INTO images (name, data, mime_type) VALUES (%s, %s, %s)",
(file.filename, image_data, mime_type)
)
# 提交事务
conn.commit()
# 关闭连接
cursor.close()
conn.close()
return 'Image uploaded successfully', 200
except Exception as e:
return str(e), 500
if __name__ == '__main__':
app.run(debug=True)
使用连接池:对于生产环境,考虑使用数据库连接池(如mysql-connector-python
的连接池或DBUtils
)
缓存机制:对于频繁访问的图片,实现缓存机制
CDN:对于大量图片,考虑使用CDN或对象存储服务
分块传输:对于大图片,考虑实现分块传输
缩略图:存储不同尺寸的缩略图以提高性能
希望这些信息对你有所帮助!如果你有任何进一步的问题,请随时提问。