2023.11.13使用flask将图片进行黑白处理(url方式进行传输)
和下述文章进行对比,实现效果相同,但是使用url方式更简便。
2023.11.12使用flask对图片进行黑白处理(base64编码方式传输)
https://editor.csdn.net/md/?articleId=134370865
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Processor</title>
</head>
<body>
<h1>Image Processor</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*" onchange="previewImage(event)">
<input type="button" value="Process" onclick="processImage()">
</form>
<h2>Preview Image</h2>
<img id="preview" src="#" alt="Preview Image">
<h2>Processed Image</h2>
<img id="processed" src="#" alt="Processed Image">
<script>
function previewImage(event) {
var input = event.target;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('preview').src = e.target.result;
};
reader.readAsDataURL(input.files[0]);
}
}
function processImage() {
var fileInput = document.querySelector('input[type="file"]');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/process', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
if (response.processed_image) {
document.getElementById('processed').src = response.processed_image;
}
}
};
xhr.send(formData);
}
</script>
</body>
</html>
from flask import Flask, render_template, request, jsonify
from PIL import Image
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process', methods=['POST'])
def process():
if 'file' not in request.files:
return jsonify({'error': 'No file part'})
file = request.files['file']
img = Image.open(file)
bw_img = img.convert('L') # 转换为黑白图片
bw_img.save('static/processed_image.jpg') # 保存处理后的图片
return jsonify({'processed_image': '/static/processed_image.jpg'})
if __name__ == '__main__':
app.run(debug=True)