编写一段python代码,使用flask框架,实现前端上传一张图片,后端获取到该图片并做缩放一半处理后返回到前端并展示,并编写相应的前端代码
时间: 2024-05-05 21:18:16 浏览: 94
好的,以下是python后端代码,使用了Pillow库进行图片处理:
```python
from flask import Flask, request, jsonify
from PIL import Image
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
if 'file' not in request.files:
return jsonify({'error': 'No file uploaded'})
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'Empty filename'})
img = Image.open(file)
img = img.resize((img.width // 2, img.height // 2))
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
return jsonify({'image': base64.b64encode(img_byte_arr).decode('utf-8')})
if __name__ == '__main__':
app.run()
```
以下是前端HTML代码,使用了jQuery和Bootstrap框架
```html
<!DOCTYPE html>
<html>
<head>
<title>Image uploader</title>
<!-- 引入Bootstrap和jQuery -->
<link href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<!-- 上传表单 -->
<h2>Upload your image</h2>
<form id="upload-form" action="/upload" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="file">Choose a file:</label>
<input type="file" name="file" id="file" accept="image/*">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<hr>
<!-- 展示处理后的图片 -->
<h2>Processed image</h2>
<div id="result"></div>
</div>
<!-- 异步请求处理后端返回的图片数据并展示 -->
<script type="text/javascript">
$(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
var form = $('#upload-form')[0];
var formData = new FormData(form);
$.ajax({
url: '/upload',
type: 'POST',
processData: false,
contentType: false,
data: formData,
success: function(response) {
var image = $('<img>').attr({
src: 'data:image/png;base64,' + response.image,
class: 'img-responsive'
});
$('#result').empty().append(image);
},
error: function(err) {
alert('Error: ' + JSON.stringify(err));
}
});
});
});
</script>
</body>
</html>
```
阅读全文