2023.11.20使用flask做一个简单图片浏览器
功能:
(1)输入指定路径,打开文件夹
(2)判断文件格式为图片
(3)在前端进行预览
(4)使用bootstrap进行简单美化
main.py
from flask import Flask, request, render_template
import osapp = Flask(__name__)@app.route('/')
def index():return render_template('index.html')@app.route('/preview_images', methods=['POST'])
def preview_images():folder_path = request.form['folder_path']images = []message = ''if os.path.isdir(folder_path):for filename in os.listdir(folder_path):if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.PNG'):images.append(os.path.join(folder_path, filename))if len(images) == 0:message = '该文件夹中没有图片文件'else:message = f'共找到{len(images)}个图片文件'else:message = '该路径不是一个文件夹'return render_template('index.html', images=images, message=message)if __name__ == '__main__':app.run()
index.html
<!DOCTYPE html>
<html>
<head><title>图片预览</title><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script><link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet"><script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script><style>.thumbnail {height: 150px;object-fit: contain;}</style>
</head>
<body><div class="container mt-3"><h2>图片预览</h2><form method="POST" action="/preview_images"><div class="input-group mb-3"><input type="text" id="folderPath" name="folder_path" class="form-control" placeholder="请输入文件夹路径"><button type="submit" class="btn btn-primary">预览</button></div></form>{% if images %}<p>{{ message }}</p><div class="row row-cols-1 row-cols-md-3 g-4">{% for image in images %}<div class="col"><div class="card"><img src="{{ image }}" class="card-img-top thumbnail" alt="..."><div class="card-body"><button type="button" class="btn btn-primary" onclick="previewImage('{{ image }}')">预览</button></div></div></div>{% endfor %}</div>{% else %}<p>{{ message }}</p>{% endif %}</div><script>function previewImage(imageUrl) {window.open(imageUrl, '_blank');}</script>
</body>
</html>