Skip to content

Leveraging Cloudinary and Flask: Creating an Interactive Image Platform

Manipulating images dynamically within web applications unlocks the potential for creative possibilities. By combining Flask with Cloudinary’s robust image management capabilities, developers can craft interactive and visually engaging applications. Let’s take a closer look at how this sample application brings together various elements and implements a dynamic image handling system using Flask and Cloudinary.

In this blog post, we’ll walk through:

  • Uploading an image from your computer to your Cloudinary account.
  • Applying an upload preset with auto tagging and eager transformation to the uploaded image.
  • Changing the color of an item within a displayed image.
  • Deleting the image from your Cloudinary account.
  1. If you haven’t yet done so, sign up for Cloudinary here.

  2. Install Cloudinary and other packages:

pip install flask
pip install dotenv
pip install cloudinary
  1. Configure Cloudinary
# Copy and paste your API environment variable
# =============================================
CLOUDINARY_URL=cloudinary://<api_key>:<api_secret>@<cloud_name>
Code language: PHP (php)
  1. In your project, create a new file called app.py, then copy and paste the following into this file to configure Cloudinary for the project:
from flask import Flask, render_template, request
from dotenv import load_dotenv

import cloudinary
import cloudinary.uploader
import cloudinary.api

load_dotenv()
app = Flask(__name__)
config = cloudinary.config(secure=True)
Code language: JavaScript (javascript)
  1. To get tags for the uploaded image in this example, we’ll use Amazon Rekognition Auto Tagging. You can subscribe to it in your Add-ons menu.
  2. Create a folder in your Media Library here and here, where you’ll upload your images. For this example, we’ll call this folder “python_examples”.
  3. Create an upload preset with the following settings:
  • Choose any name you prefer for the preset (in this example, it’s called “python”).
  • Add the name of the folder you just created in Step 6, under Folder.
  • Turn Use filename or externally defined Public ID to ON.
  • Navigate to Media analysis and AI and under Categorization, check the box for Amazon Rekognition Auto Tagging.
  • Save the upload preset.

In the upcoming sections, we’ll review the code snippets and explore their respective functions.

In the following code, we’ll upload an image from our computer to our Cloudinary account.

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        
        if file:
            response=cloudinary.uploader.upload(file, 
                                 upload_preset = "python",
                                 unique_filename = True, 
                                 overwrite=True,
                                 eager=[{"width": 500, "crop": "fill"}])

            image_url = response['eager'][0]['secure_url']
            tags = response['info']['categorization']['aws_rek_tagging']['data'][:3]

            return render_template('index.html', image_url=image_url, tags=tags)

    return render_template('index.html')
Code language: PHP (php)

Using Cloudinary’s upload method, we can define some settings for uploading files. In this example, we’ll use the upload preset that we created in the previous step, in order to apply Rekognition Auto Tagging and to upload to the defined folder.

We’ll also apply an eager transformation to the uploaded image that defines that the image has to be cropped to fill a 500 pixels wide square.

In the image_url variable, we’ll get the URL of the uploaded image, and in the tags variable it will list the top three tags for us that we can display on the site.

The next section of the code, we can leverage the Generative Recolor feature.

@app.route('/recolor', methods=['POST'])
def recolor():
    if request.method == 'POST':
        image_url = request.form.get('image_url')
        public_id = "/".join(image_url.split('/')[-2:])[:-4]
        color = request.form['color']
        color_for_url = color[1:]
        chosen_object = request.form['object']
        transformation = f"gen_recolor:prompt_{chosen_object};to-color_{color_for_url}/c_fill,w_500"
        
        recolor_url = cloudinary.utils.cloudinary_url(public_id, effect=transformation)[0]
        
        response = cloudinary.api.resource(public_id, tags=True)
        tags = response['info']['categorization']['aws_rek_tagging']['data'][:3]

        return render_template ('index.html', recolor_url=recolor_url, image_url=image_url, tags=tags)
Code language: PHP (php)

To generate an image URL that has the recolor capabilities, we first have to define what we want to recolor on our image. We’ll grab that information from the user via the chosen_object variable. We’ll also need the color that we plan to apply to the image. This is provided via a color picker input field from the user, and the color_for_url is trimming the # symbol from the color hex code to make it work in the URL forming.

After identifying both the object and color, we’ll have to reconstruct the URL with the given syntax in the transformation variable.

The uploaded image could be removed from your Cloudinary account with the following code:

@app.route('/delete', methods=['POST'])
def delete_image():
    if request.method == 'POST':
        image_url = request.form.get('image_url')
        public_id = "/".join(image_url.split('/')[-2:])[:-4]
        result = cloudinary.uploader.destroy(public_id)
        return render_template ('index.html')
Code language: JavaScript (javascript)

To delete an image, we’ll need the public ID of the image, and the folder as well, where the image is stored. The code above grabs the URL and extracts the folder and image ID from the end of the URL.

Running this code simply removes the uploaded file from our Media Library.

This example app showcases several of Cloudinary’s image management capabilities. The upload was done purely with Python; however, you can also use Cloudinary’s Upload Widget to customize and expand the uploading possibilities. While we use the Rekognition Auto Tagging feature here, there are other add-ons and AI features to boost your productivity and engagement with images and videos.

You can find the full app in this GitHub repo. Fork it and apply more of your own transformation to unleash the full potential of your media.

If you found this article helpful and want to discuss it in more detail, head over to Cloudinary Community forum and its associated Discord.

Back to top

Featured Post