Skip to content

Image resize

Manish Sah edited this page Oct 3, 2020 · 1 revision

We will move the logic for saving images in our project from routes to utils.py , so that our code will be more readable. lets create utils.py in blog package and move the image logic from route to utils

blog/utils.py

import os
from flask_login import current_user

from blog import app


def save_image(picture_form_data):
    filename, extension = os.path.splitext(picture_form_data.filename)
    new_file_name = current_user.username + extension
    file_path = os.path.join(app.root_path, 'static/profile_pictures', new_file_name)
    picture_form_data.save(file_path)
    return new_file_name 

Now our profile routes will be like this

blog/routes.py

.
@app.route("/profile", methods=["GET", "POST"])
@login_required
def profile():
    form = ProfileUpdateForm()
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.email = form.email.data
        if form.picture.data:
            current_user.image_file = save_image(form.picture.data)
        db.session.commit()
        flash('Your profile was updated', 'success')
        return redirect("/profile")
    form.username.data = current_user.username
    form.email.data = current_user.email
    return render_template('profile.html', title_name='profile', form=form)

Resizing image

Currently we are storing the image uploaded by user as it is. lets resize the image before storing it so that we can save memory in our system.

we will use pillow library for image manipulation.

pip install pillow

we will import Image class from PIL package and resize the image as follows:

blog/utils.py

import os
from flask_login import current_user
from PIL import Image
from blog import app


def save_image(picture_form_data):
    filename, extension = os.path.splitext(picture_form_data.filename)
    new_file_name = current_user.username + extension
    file_path = os.path.join(app.root_path, 'static/profile_pictures', new_file_name)
    output_size = (300, 300)
    resized_image = Image.open(picture_form_data)
    resized_image.thumbnail(output_size)
    resized_image.save(file_path)
    return new_file_name

Implementation can be found over this commit

Clone this wiki locally