Cloudinary Blog

ChatBot for Image Manipulation

ChatBot for Image Manipulation

Bots - which have been around for a long time and perform different functions - are gradually replacing traditional applications. Consider Internet bots, also known as web robots, as software applications that run automated tasks over the internet, such as crawling websites and indexing search engines. Slack, the popular business messaging service, also popularized the use of bots for almost anything, from tracking stand-ups and sending reminders, to activating continuous integration and different types of activities.

Chatbots are the new trendy type of bots and they are becoming ubiquitous. Several organizations around the world are now taking advantage of chatbots to simulate conversations between users and computers. With chatbots, you can eliminate the need to have a human on the other end, for basic customer enquiries or requests. Messaging platforms, such as WeChat and Facebook Messenger, are massive advocates of chatbots.

The Image Editing Chatbot Overview

Chatbot screen

The Image Editing Chatbot is a simple prototype/experiment that can quickly solve your image editing challenges. Let’s examine a scenario here to illustrate my point better:

You work for an ecommerce store that has hundreds of images that are being delivered to different layouts, devices, screens and bandwidths. Manually creating these variants can be resource intensive and not scalable.

However, creating multiple variants of an image being delivered across different layouts, devices and bandwidth using an image manipulation chatbot could help. In fact, you can avoid taking on some tasks by simply assigning the URL of the deployed chatbot for others to use. One of the main resulting benefits is that non-technical folks can comfortably use it to solve their image editing challenges, as well.

Some Tech Required

Let’s analyze the technology behind the chatbot.

Before we start, you will want to clone the chatbot from GitHub.

Follow the instructions on the README and execute the commands displayed on the repo in the right sequence. Are you having fun yet?

Chatbot screen

I used the command please overlay ACME logo at the south-west corner and the resulting image was the previously uploaded image with ACME logo placed on it as specified in the command.

Chatbot screen

The first image is the original size of the uploaded image. I entered the command please set the width to 500 and it immediately cropped the image and returned the smaller size.

Easy, isn’t it? Next, let’s talk about the stack.

The chatbot is built with:

  • React - for building out the front-end of the image editing tool
  • Node - for building the backend that interacts with the Cloudinary service for image editing
  • Cloudinary - a cloud-based, end-to-end image and video management solution that enables uploads, storage, administration, image manipulation and delivery
  • PubNub - a service for developing Real-time applications

Now, let’s go more in-depth. Open up the source code.

Check out the src/App.js file.

render() {
        return (
            <div className="vbox fill">
                <div className="scroll grow" id="scroll">
                    {this.renderHistory()}
                </div>
                <div className="hbox">
                    <input ref='text' type="text" className="grow"
                           value={this.state.currentText} onChange={this.textEdit.bind(this)}
                           onKeyDown={this.textKeydown.bind(this)}
                    />
                    <button onClick={this.sendMessage.bind(this)}>send</button>
                    <button onClick={this.showUploader.bind(this)}>Upload Image</button>
                </div>
            </div>
        );
    }

    showUploader() {
        var cloudinary = window.cloudinary;
        cloudinary.openUploadWidget({ cloud_name: 'pubnub', upload_preset: 'mcipauzl'},
            (error, result) => {
                console.log(error, result);
                console.log("the upload path is", result[0].path);
                ImageService.setImagePath(result[0].path);
            });
    }

render() is responsible for displaying the send, Upload Image buttons and the history of messages sent in the chatbot.

showUploader() is responsible for calling the Cloudinary upload widget. Take a look at the image below:

Note: You can change the cloud_name and upload_preset to the credentials from your Cloudinary dashboard.

Upload Widget

Check out the src/ImageService.js.

You can change the publishKey and subscribeKey values to the credentials from our PubNub dashboard.

The ImageService is responsible for communicating with PubNub channels on setting and getting image paths in real time.

Check out the src/ParserService.js. The ParserService is a giant service responsible for analyzing keywords in the commands such as upload, display, show, resize, reset, make, overlay and processing it.

src/ParserService.js

if(command.action === 'overlay') {
            console.log("doing an overlay");
            var fname = command.target;
            fname = "sample";
            var scale = 1.0;
            scale = 0.2;
            var grav = command.direction;
            if(command.direction === 'southwest') {
                grav = 'south_west';
            }
            transforms.push("l_"+fname+",w_"+scale+",g_"+grav);
        }

Taking the overlay action and applying the needed Cloudinary transformation.

//apply the context
        if(!context.format) context.format = 'jpg';
        if(context.width) {
            transforms.push("w_"+context.width);
        }
        if(context.autoContrast) transforms.push("e_auto_contrast");
        if(context.autoSharpen) transforms.push("e_sharpen");
        if(context.crop) {
            transforms.push("w_"+context.width+",h_"+context.width
                +",c_fill,g_"+context.gravity);
        }

        console.log("final context is",context);


        //generate the final url
        var apiUrl = 'https://res.cloudinary.com/' +
            cloudName + '/' + resource + '/' + operation + '/';
        if(transforms.length > 0) {
            apiUrl += transforms.join("/") + "/"
        }
        var filename = context.path.substring(0,context.path.lastIndexOf('.'));
        apiUrl += filename  + '.' + context.format;
        return apiUrl;

It obtains the required transformation parameters and generates the Cloudinary URL with those parameters.

The server.js is simply responsible for processing the commands from the frontend via the parser service and returning the right responses.

Cloudinary Transformations

Using Cloudinary, you can quickly and easily optimize your images, regardless of your programming language preference. Cloudinary automatically performs certain optimizations on all transformed images by default. Its integrated, fast CDN delivery also helps to get all the image resources to your users quickly.

Let’s explore some image manipulation techniques and transformations that are effortless using Cloudinary:

Cropping:

Ruby:
cl_image_tag("lady.jpg", :width=>400, :height=>400, :crop=>"crop")
PHP:
cl_image_tag("lady.jpg", array("width"=>400, "height"=>400, "crop"=>"crop"))
Python:
CloudinaryImage("lady.jpg").image(width=400, height=400, crop="crop")
Node.js:
cloudinary.image("lady.jpg", {width: 400, height: 400, crop: "crop"})
Java:
cloudinary.url().transformation(new Transformation().width(400).height(400).crop("crop")).imageTag("lady.jpg")
JS:
cl.imageTag('lady.jpg', {width: 400, height: 400, crop: "crop"}).toHtml();
jQuery:
$.cloudinary.image("lady.jpg", {width: 400, height: 400, crop: "crop"})
React:
<Image publicId="lady.jpg" >
  <Transformation width="400" height="400" crop="crop" />
</Image>
Angular:
<cl-image public-id="lady.jpg" >
  <cl-transformation width="400" height="400" crop="crop">
  </cl-transformation>
</cl-image>
.Net:
cloudinary.Api.UrlImgUp.Transform(new Transformation().Width(400).Height(400).Crop("crop")).BuildImageTag("lady.jpg")
Android:
MediaManager.get().url().transformation(new Transformation().width(400).height(400).crop("crop")).generate("lady.jpg")
lady

Image overlay:

Ruby:
cl_image_tag("lady.jpg", :transformation=>[
  {:width=>500, :crop=>"scale"},
  {:overlay=>"cloudinary_icon", :width=>0.9, :gravity=>"south_east", :opacity=>70, :effect=>"brightness:50", :crop=>"scale"}
  ])
PHP:
cl_image_tag("lady.jpg", array("transformation"=>array(
  array("width"=>500, "crop"=>"scale"),
  array("overlay"=>"cloudinary_icon", "width"=>0.9, "gravity"=>"south_east", "opacity"=>70, "effect"=>"brightness:50", "crop"=>"scale")
  )))
Python:
CloudinaryImage("lady.jpg").image(transformation=[
  {"width": 500, "crop": "scale"},
  {"overlay": "cloudinary_icon", "width": 0.9, "gravity": "south_east", "opacity": 70, "effect": "brightness:50", "crop": "scale"}
  ])
Node.js:
cloudinary.image("lady.jpg", {transformation: [
  {width: 500, crop: "scale"},
  {overlay: "cloudinary_icon", width: "0.9", gravity: "south_east", opacity: 70, effect: "brightness:50", crop: "scale"}
  ]})
Java:
cloudinary.url().transformation(new Transformation()
  .width(500).crop("scale").chain()
  .overlay("cloudinary_icon").width(0.9).gravity("south_east").opacity(70).effect("brightness:50").crop("scale")).imageTag("lady.jpg")
JS:
cl.imageTag('lady.jpg', {transformation: [
  {width: 500, crop: "scale"},
  {overlay: "cloudinary_icon", width: "0.9", gravity: "south_east", opacity: 70, effect: "brightness:50", crop: "scale"}
  ]}).toHtml();
jQuery:
$.cloudinary.image("lady.jpg", {transformation: [
  {width: 500, crop: "scale"},
  {overlay: "cloudinary_icon", width: "0.9", gravity: "south_east", opacity: 70, effect: "brightness:50", crop: "scale"}
  ]})
React:
<Image publicId="lady.jpg" >
  <Transformation width="500" crop="scale" />
  <Transformation overlay="cloudinary_icon" width="0.9" gravity="south_east" opacity="70" effect="brightness:50" crop="scale" />
</Image>
Angular:
<cl-image public-id="lady.jpg" >
  <cl-transformation width="500" crop="scale">
  </cl-transformation>
  <cl-transformation overlay="cloudinary_icon" width="0.9" gravity="south_east" opacity="70" effect="brightness:50" crop="scale">
  </cl-transformation>
</cl-image>
.Net:
cloudinary.Api.UrlImgUp.Transform(new Transformation()
  .Width(500).Crop("scale").Chain()
  .Overlay("cloudinary_icon").Width(0.9).Gravity("south_east").Opacity(70).Effect("brightness:50").Crop("scale")).BuildImageTag("lady.jpg")
Android:
MediaManager.get().url().transformation(new Transformation()
  .width(500).crop("scale").chain()
  .overlay("cloudinary_icon").width(0.9).gravity("south_east").opacity(70).effect("brightness:50").crop("scale")).generate("lady.jpg")
Lady

Text overlay:

Ruby:
cl_image_tag("lady.jpg", :transformation=>[
  {:width=>500, :crop=>"scale"},
  {:overlay=>"text:Arial_50:Awesome"}
  ])
PHP:
cl_image_tag("lady.jpg", array("transformation"=>array(
  array("width"=>500, "crop"=>"scale"),
  array("overlay"=>"text:Arial_50:Awesome")
  )))
Python:
CloudinaryImage("lady.jpg").image(transformation=[
  {"width": 500, "crop": "scale"},
  {"overlay": "text:Arial_50:Awesome"}
  ])
Node.js:
cloudinary.image("lady.jpg", {transformation: [
  {width: 500, crop: "scale"},
  {overlay: "text:Arial_50:Awesome"}
  ]})
Java:
cloudinary.url().transformation(new Transformation()
  .width(500).crop("scale").chain()
  .overlay("text:Arial_50:Awesome")).imageTag("lady.jpg")
JS:
cl.imageTag('lady.jpg', {transformation: [
  {width: 500, crop: "scale"},
  {overlay: "text:Arial_50:Awesome"}
  ]}).toHtml();
jQuery:
$.cloudinary.image("lady.jpg", {transformation: [
  {width: 500, crop: "scale"},
  {overlay: "text:Arial_50:Awesome"}
  ]})
React:
<Image publicId="lady.jpg" >
  <Transformation width="500" crop="scale" />
  <Transformation overlay="text:Arial_50:Awesome" />
</Image>
Angular:
<cl-image public-id="lady.jpg" >
  <cl-transformation width="500" crop="scale">
  </cl-transformation>
  <cl-transformation overlay="text:Arial_50:Awesome">
  </cl-transformation>
</cl-image>
.Net:
cloudinary.Api.UrlImgUp.Transform(new Transformation()
  .Width(500).Crop("scale").Chain()
  .Overlay("text:Arial_50:Awesome")).BuildImageTag("lady.jpg")
Android:
MediaManager.get().url().transformation(new Transformation()
  .width(500).crop("scale").chain()
  .overlay("text:Arial_50:Awesome")).generate("lady.jpg")
Awesome/lady

Blur:

Ruby:
cl_image_tag("flowers.jpg", :effect=>"blur:300")
PHP:
cl_image_tag("flowers.jpg", array("effect"=>"blur:300"))
Python:
CloudinaryImage("flowers.jpg").image(effect="blur:300")
Node.js:
cloudinary.image("flowers.jpg", {effect: "blur:300"})
Java:
cloudinary.url().transformation(new Transformation().effect("blur:300")).imageTag("flowers.jpg")
JS:
cl.imageTag('flowers.jpg', {effect: "blur:300"}).toHtml();
jQuery:
$.cloudinary.image("flowers.jpg", {effect: "blur:300"})
React:
<Image publicId="flowers.jpg" >
  <Transformation effect="blur:300" />
</Image>
Angular:
<cl-image public-id="flowers.jpg" >
  <cl-transformation effect="blur:300">
  </cl-transformation>
</cl-image>
.Net:
cloudinary.Api.UrlImgUp.Transform(new Transformation().Effect("blur:300")).BuildImageTag("flowers.jpg")
Android:
MediaManager.get().url().transformation(new Transformation().effect("blur:300")).generate("flowers.jpg")
Flowers

Artistic Filter effects:

Ruby:
cl_image_tag("flowers.jpg", :effect=>"art:sizzle")
PHP:
cl_image_tag("flowers.jpg", array("effect"=>"art:sizzle"))
Python:
CloudinaryImage("flowers.jpg").image(effect="art:sizzle")
Node.js:
cloudinary.image("flowers.jpg", {effect: "art:sizzle"})
Java:
cloudinary.url().transformation(new Transformation().effect("art:sizzle")).imageTag("flowers.jpg")
JS:
cl.imageTag('flowers.jpg', {effect: "art:sizzle"}).toHtml();
jQuery:
$.cloudinary.image("flowers.jpg", {effect: "art:sizzle"})
React:
<Image publicId="flowers.jpg" >
  <Transformation effect="art:sizzle" />
</Image>
Angular:
<cl-image public-id="flowers.jpg" >
  <cl-transformation effect="art:sizzle">
  </cl-transformation>
</cl-image>
.Net:
cloudinary.Api.UrlImgUp.Transform(new Transformation().Effect("art:sizzle")).BuildImageTag("flowers.jpg")
Android:
MediaManager.get().url().transformation(new Transformation().effect("art:sizzle")).generate("flowers.jpg")
Flowers

Note: There are several effects, such as athena, audrey, frost, quartz, zorro and more. Check out the docs for more filter effects.

And consult the Cloudinary documentation to see a wide array image transformation techniques.

Conclusion

The Image Manipulation Chatbot can be further improved to provide more functionality. We can have the chatbot analyze images and detect objects in them. In addition, we can connect the chatbot with Google Cloud Speech API to enable a user to speak the commands to the bot. The chatbot will convert audio to text, pass the text onto the Parser Service, process and return the desired results.

One thing to consider, though. The chatbot understands commands written only in English. What about making it multilingual so that our Spanish, French, Dutch or Chinese colleagues could write commands in their language and have the chatbot process and work correctly? Awesome right? Google Cloud Translation Service might just come in handy here.

Building a chatbot is not rocket science. Harnessing the potential and competence of serverless backends, such as Cloudinary and PubNub, can empower you to automate tedious, time-consuming tasks by building interactive software that simply works.

What would you like a Cloudinary-powered Chatbot to do? Let me know in the comments section.

Recent Blog Posts

Analyze and auto tag images with Amazon Rekognition

Knowledge is power. And if you allow your users to upload images, you also probably want to better understand what their images contain. Whether a photo is of a building, people, animals, celebrities, or a product, image processing and analysis can assist in further comprehension. The benefits of this knowledge can go beyond "merely" categorizing your content and making your image library searchable: drawing insights from user generated content can be very useful! What better way to learn more about your users than to analyze the images they upload and find out what they care about and then have the ability to display relevant content to them according to their interests or even match them with other users that share similar interests.

Read more
Automatically moderate your user uploaded images

Allowing your users to upload their own images to your website can increase user engagement, retention and monetization. However, allowing your users to upload any image they want to, may lead to some of your users uploading inappropriate images to your application. These images may offend other users or even cause your site to violate standards or regulations.

Read more
Cloudinary Uses Scale API to Focus on Image Compression

Here at Cloudinary, we provide a cloud-based tool that enables our users to compress images and video for their websites and apps. Our goal is to preserve the visual integrity of the content, but deliver the smallest file size to any device or browser to ultimately optimize website performance and end user satisfaction.

Read more
CloudinaryAndroid SDK

Developing applications for mobile consumption requires facing, and overcoming, some difficult challenges. Apps need to limit their RAM, CPU and battery usage while still performing the required tasks in a reasonable time frame. If too many background tasks are running, the mobile device can become sluggish, with the battery running out very quickly. Coordination with other apps is crucial to keep the device responsive and make the battery last longer.

Read more
forLoop: Nigeria Event on Building for The Next Billion Users

TL;DR

Since Google shared their intent for the next billion internet users, some African developers thought this was pointing right at them and they needed to act fast. The mission to bring the next billion users from Africa to the internet kicked off a storm of enthusiasm. This community event turned into a success story and this is a summary of what happened.

Read more