-
Notifications
You must be signed in to change notification settings - Fork 13
/
app.py
66 lines (51 loc) · 1.78 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from flask import Flask, flash, get_flashed_messages, make_response, redirect, render_template_string, request
from os import path, unlink
from PIL import Image
import tempfile
app = Flask(__name__)
app.secret_key = "0123456789ABCDEF"
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files.get('image', None)
if not file:
flash('No image found')
return redirect(request.url)
filename = file.filename
ext = path.splitext(filename)[1]
if (ext not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']):
flash('Invalid extension')
return redirect(request.url)
tmp = tempfile.mktemp("test")
img_path = "{}.{}".format(tmp, ext)
file.save(img_path)
img = Image.open(img_path)
w, h = img.size
ratio = 256.0 / max(w, h)
resized_img = img.resize((int(w * ratio), int(h * ratio)))
resized_img.save(img_path)
r = make_response()
r.data = open(img_path, "rb").read()
r.headers['Content-Disposition'] = 'attachment; filename=resized_{}'.format(filename)
unlink(img_path)
return r
return render_template_string('''
<!doctype html>
<title>Image Resizer</title>
<h1>Upload an Image to Resize</h1>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method=post enctype=multipart/form-data>
<p><input type=file name=image>
<input type=submit value=Upload>
</form>
''')
if __name__ == '__main__':
app.run(threaded=True, port=8000, host="0.0.0.0")