A Quick Guide to Smart Cropping in Your WYSIWYG Editor

What if your WYSIWYG editor could automatically ensure every image looked just right? Smart cropping is a feature that makes it possible. It can automatically crop any unwanted parts of an image while keeping the most important parts. This makes smart cropping highly valuable for applications that constantly deal with image uploads and processing, such as blogs and social media platforms. However, implementing smart cropping from scratch is not always the best course of action. That’s why in this guide, I’ll show you how you can quickly implement smart cropping in your WYSIWYG HTML editor.

Key Takeaways

  • Smart cropping is an important part of image-heavy applications
  • Smart crop an image to focus on specific objects within it while reducing its size
  • Quickly implement smart cropping with Froala WYSIWYG editor and Filestack
  • Change detection modes (face, object, auto) as needed using Filestack
  • Smart cropping ensures consistency, efficiency, and better control

What is Smart Cropping?

Smart cropping is a fairly novel feature in applications that automatically adjusts the size of your image. What makes this different from regular dynamic cropping is that it can focus on the main object of the photo. With it, developers don’t have to specify coordinates to determine the cropping area. Instead, they can just specify a size and let smart cropping do its job. This makes it perfect for applications such as blogs, CMS, LMS, and social media platforms.

For example, you can implement smart cropping for profile pictures. When a user uploads a photo, an application with smart cropping can focus on the user’s face while automatically resizing the image. This process is much faster than having the user manually crop and focus the image. Note, however, that you should still put an option for the user to manually crop images in case. Now, let’s check how we can implement this powerful feature in WYSIWYG editors.

How to Implement Smart Cropping within a WYSIWYG Editor

Setting up Your WYSIWYG Editor

First, we’ll need to initialize our editor. To do this, add the following code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Smart Crop Using Froala and Filestack</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link href="https://cdn.jsdelivr.net/npm/froala-editor@latest/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.css" />
</head>

<body>
    <div class="container-fluid vh-100">
	<div class="row h-100">
            <div class="col-md-6 mx-auto my-auto">
                <div id="froala-editor"></div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
    <script src="https://static.filestackapi.com/filestack-js/3.32.0/filestack.min.js"></script>
    <script src="https://static.filestackapi.com/filestack-drag-and-drop-js/1.1.1/filestack-drag-and-drop.min.js"></script>
    <script src="https://static.filestackapi.com/transforms-ui/2.x.x/transforms.umd.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@latest/js/froala_editor.pkgd.min.js"></script>
    <script src="js/index.js"></script>
</body>
</html>

The only important parts here are loading the Froala and Filestack libraries and creating the div element that will contain the editor. After creating your HTML, insert the following code to your JavaScript:

new FroalaEditor('#froala-editor',{
    filestackOptions: {
        filestackAPI: 'YourFilestackAPIKey',
        uploadToFilestackOnly: true,
        pickerOptions: {
            accept: ['image/*'],
            fromSources: ['local_file_system']
        }
    },
    toolbarButtons: {
        'moreRich': {
            'buttons': ['openFilePickerImageOnly', 'insertLink', 'insertTable', 'emoticons', 'specialCharacters', 'insertHR'],
            'buttonsVisible': 3
        },
        'moreText': {
            'buttons': ['bold', 'italic', 'underline', 'fontFamily', 'fontSize', 'textColor', 'backgroundColor', 'clearFormatting']
        },
        'moreParagraph': {
            'buttons': ['alignLeft', 'alignCenter', 'formatOLSimple', 'alignRight', 'alignJustify', 'formatOL', 'formatUL', 'paragraphFormat', 'paragraphStyle', 'lineHeight', 'outdent', 'indent', 'quote']
        },
        'moreMisc': {
            'buttons': ['undo', 'redo', 'fullscreen', 'selectAll', 'html', 'help'],
            'align': 'right',
            'buttonsVisible': 2
        }
    },
    events: {
        'filestack.uploadedToFilestack': function (response) {
        },
        'filestack.uploadFailedToFilestack': function (response) {
            console.log(response);
        },
    },
    heightMin: 500,
    heightMax: 1000
});

This declares a FroalaEditor instance in the div element that we created earlier. Furthermore, consider the editor’s properties, in which we state Filestack’s options and Froala’s toolbar buttons, events, and size. For the options, set your API key, which you can get by creating a free Filestack account. Additionally, set the picker options that best fit your needs. When you run the application with this setup, you will see the Froala editor with the Filestack file picker icon. At this point, the editor is ready to leverage Filestack’s image transformation features—but enabling smart cropping requires one more step.

Adding Smart Crop Logic

The next step is to add the logic for smart cropping. This is achieved through Froala’s “events” property, specifically using the ‘filestack.uploadedToFilestack‘ event. This event is triggered after a successful upload, allowing you to process the uploaded image further.

const originalFileURL = response.filesUploaded[0].url;
const croppedFileURL = `https://cdn.filestackcontent.com/smart_crop=width:400,height:400/${originalFileURL}`;
const editor = FroalaEditor.INSTANCES[0];
editor.image.insert(croppedFileURL, true, { link: croppedFileURL, alt: 'Cropped Image' });
console.log("Cropped image inserted:", croppedFileURL);

In the code, the first line extracts the URL of the uploaded image from the response object. Next, we generate the URL of the cropped image using Filestack’s Smart Crop transformation. Here, we must specify the dimensions of the resulting image (in this case, 400×400 pixels). Moreover, we can specify additional options for the process, such as the cropping mode (face, object, or auto). Finally, we insert the cropped image back into the editor using the “editor.image.insert” method. With this logic in place, your WYSIWYG editor not only supports image uploads but also smart cropping, enhancing efficiency and precision.

Testing the Smart Crop Feature within the WYSIWYG Editor

Let’s test Froala and Filestack’s smart crop feature. Run the application, and you should see the editor with the Filestack icon. Click on the icon and upload an image through Filestack. Afterwards, you should see both the unprocessed photo (which we’ve kept for comparison) and the cropped version. Here’s a quick demo of the smart crop feature:

A demo that showcases Filestack's smart cropping capabilities within Froala WYSIWYG editor

In the GIF above, I uploaded a landscape image of a cat. After uploading it, Filestack’s smart crop was able to keep the most important part of the image, generating a 400×400 cropped version. Note that the unprocessed image also remained because Filestack doesn’t overwrite it. From here, you can customize the smart cropping experience further. For instance, you can clear the unprocessed image and store the URL of the processed version. If you’re building a social media platform, you can also customize smart cropping to focus more on faces instead of objects. You can even chain this with other Filestack processing tasks, such as NSFW scanning, virus detection, image enhancements, and more using Filestack Workflows.

Wrapping up: Smarter Tools for Smarter WYSIWYG Editors

Smart cropping is a vital and modern feature for content-centric applications. Thus, developers can benefit from learning how to integrate this feature in different applications. Doing so is not always straightforward, but with the right tools, you can implement smart cropping in a matter of minutes. With smart cropping seamlessly integrated into your WYSIWYG editor, the possibilities for customization and enhancement are endless. Whether you’re building a social media platform or a content management tool, smart cropping helps promote efficient workflows and user-friendly experiences. Get your Filestack API here. Happy coding!

Posted on December 5, 2024

Aaron Dumon

Aaron Dumon is an expert technical writer focusing on JavaScript WYSIWYG HTML Editors.

No comment yet, add your voice below!


Add a Comment

Your email address will not be published. Required fields are marked *

    Hide Show