Skip to content

Instantly share code, notes, and snippets.

@ilkermanap
Created December 5, 2019 11:39
Show Gist options
  • Select an option

  • Save ilkermanap/11e8cc95c36591c04e2ac9b55e0ba0d9 to your computer and use it in GitHub Desktop.

Select an option

Save ilkermanap/11e8cc95c36591c04e2ac9b55e0ba0d9 to your computer and use it in GitHub Desktop.
flask image scale using PIL
import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
from flask import send_from_directory
UPLOAD_FOLDER = '/tmp/'
ALLOWED_EXTENSIONS = { 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
from PIL import Image
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def scale_image(filename):
img = Image.open(filename)
img.thumbnail((256,256), Image.ANTIALIAS)
path = filename[:filename.rfind("/")+1]
name = filename[filename.rfind("/")+1:]
img.save(path + "thumb_" + name)
return "thumb_" + name
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
newname = scale_image(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=newname))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment