image objects in python

Solutions on MaxInterview for image objects in python by the best coders in the world

showing results for - "image objects in python"
Antonio
24 Apr 2019
1from flask import Flask, render_template, redirect, url_for, send_from_directory, request
2from flask_bootstrap import Bootstrap
3from PIL import Image
4from werkzeug.utils import secure_filename
5import os
6
7app = Flask(__name__)
8Bootstrap(app)
9
10APP_ROOT = os.path.dirname(os.path.abspath(__file__))
11images_directory = os.path.join(APP_ROOT, 'images')
12thumbnails_directory = os.path.join(APP_ROOT, 'thumbnails')
13if not os.path.isdir(images_directory):
14    os.mkdir(images_directory)
15if not os.path.isdir(thumbnails_directory):
16    os.mkdir(thumbnails_directory)
17
18
19@app.route('/')
20def index():
21    return render_template('index.html')
22
23
24@app.route('/gallery')
25def gallery():
26    thumbnail_names = os.listdir('./thumbnails')
27    return render_template('gallery.html', thumbnail_names=thumbnail_names)
28
29
30@app.route('/thumbnails/<filename>')
31def thumbnails(filename):
32    return send_from_directory('thumbnails', filename)
33
34
35@app.route('/images/<filename>')
36def images(filename):
37    return send_from_directory('images', filename)
38
39
40@app.route('/public/<path:filename>')
41def static_files(filename):
42    return send_from_directory('./public', filename)
43
44
45@app.route('/upload', methods=['GET', 'POST'])
46def upload():
47    if request.method == 'POST':
48        for upload in request.files.getlist('images'):
49            filename = upload.filename
50            # Always a good idea to secure a filename before storing it
51            filename = secure_filename(filename)
52            # This is to verify files are supported
53            ext = os.path.splitext(filename)[1][1:].strip().lower()
54            if ext in {'jpg', 'jpeg', 'png'}:
55                print('File supported moving on...')
56            else:
57                return render_template('error.html', message='Uploaded files are not supported...')
58            destination = '/'.join([images_directory, filename])
59            # Save original image
60            upload.save(destination)
61            # Save a copy of the thumbnail image
62            image = Image.open(destination)
63            image.thumbnail((300, 170))
64            image.save('/'.join([thumbnails_directory, filename]))
65        return redirect(url_for('gallery'))
66    return render_template('upload.html')
67
68
69if __name__ == '__main__':
70    app.run(host='0.0.0.0', port=os.environ.get('PORT', 3000))