2023.11.22使用flask做一个简单的图片浏览器
功能:
实现图片浏览(翻页)功能
程序页面:
程序架构:
注意:在flask中常会使用src=“{{ url_for(‘static’, filename=‘images/’ + image) }}”,这段代码是在Flask框架中用于获取静态文件的URL的。在Flask中,静态文件通常存放在static文件夹中,比如CSS、JavaScript或者图片文件等。url_for(‘static’, filename=‘images/’ + image)这段代码会生成一个对应静态文件的URL,其中’static’是指定静态文件夹的名称,‘images/’ + image是指定文件夹中图片的路径。
如果image是一个变量,那么在渲染模板的时候就会根据实际的image的值来生成对应的URL。这个URL可以在前端页面中引用,用于加载静态图片文件。
注意静态文件夹如果要改变需要另外声明。
main.py
import os
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/preview', methods=['POST'])
def preview():
image_name = request.form['image_name']
image_dir = os.path.dirname(os.path.abspath(__file__)) + '/static/uploads'
image_list = sorted(os.listdir(image_dir))
current_index = image_list.index(image_name)
prev_index = current_index - 1 if current_index > 0 else None
next_index = current_index + 1 if current_index < len(image_list) - 1 else None
prev_image_name = image_list[prev_index] if prev_index is not None else None
next_image_name = image_list[next_index] if next_index is not None else None
image_url = f'/static/uploads/{image_name}'
return render_template('preview.html', image_name=image_name, image_url=image_url, prev_image_name=prev_image_name, next_image_name=next_image_name)
if __name__ == '__main__':
app.run(debug=True)
preview.html
<!DOCTYPE html>
<html>
<head>
<title>Image Preview</title>
<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>
body {
padding: 20px;
}
img {
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<h2>Image Preview: {{ image_name }}</h2>
<div>
<img src="{{ image_url }}" class="img-fluid" alt="Preview">
</div>
<div class="btn-group mt-2" role="group" aria-label="Image Navigation">
<form action="/preview" method="post">
{% if prev_image_name %}
<input type="hidden" name="image_name" value="{{ prev_image_name }}">
<input type="submit" class="btn btn-primary" value="Prev">
{% endif %}
</form>
<form action="/preview" method="post">
{% if next_image_name %}
<input type="hidden" name="image_name" value="{{ next_image_name }}">
<input type="submit" class="btn btn-primary" value="Next">
{% endif %}
</form>
</div>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<head>
<title>Image Preview</title>
</head>
<body>
<h2>Enter Image Name</h2>
<form action="/preview" method="post">
<input type="text" name="image_name" placeholder="Enter Image Name">
<button type="submit">Preview</button>
</form>
</body>
</html>