Site icon Filestack Blog

Chaining Image Transformations Together with React

Editing images is a routine component of web development. As developers, we often have to resize or crop an image to fit a certain space. We may need to upscale an image to improve the resolution on a screen size, or compress an image to save bandwidth and reduce load time. Furthermore, social sites like Instagram and Snapchat have opened Pandora’s Box for the realm of user image editing, making the need to supply users with the tools to apply filters and effects to their images a basic requirement.

 

The fact is, we are rarely applying just one change to an image.  To make a profile picture, we would like to first detect the face, then crop around it, then apply a circle border, and then resize for the different places it will be appearing on our application. To post an item to an online store, we would like to edit it and apply filters to ensure it looks stunning and will elicit the right emotional reaction from the customer.

 

Of course, there are a series of tools (Photoshop, Sketch, Canva) that allow us to edit images individually, but they only go so far when it comes to handling images at scale. And free resources like Imagemagick are extraordinarily helpful, but also come with drawbacks like clunkiness, limited abilities, and security risks.

 

In response, we’ve built Filestack’s Image Processing Engine so you can chain multiple image conversion tasks together. You can crop, resize, detect faces, tag images, apply filters, and more, all in conjunction with each other. The power to chain image transformations enables you to simplify your workload and harness immense capabilities with very slight alterations to your code.

 

For the next portion of the article, I will demonstrate how to use Filestack’s API to create a React Application in which you can apply multiple conversion tasks to images as they are uploaded.

Chaining Transformation Tasks in a React App

The image editing application we will create together demonstrates compressing, resizing, and sharpening images. However, you can easily swap in whatever image transformations you like from Filestack’s image transformation library.

This is what the application will look like:

Homepage
Image Upload Form

As always, you can find the complete sample code on my github.

Upload a Picture

Let’s start with the image uploading component. In this application, the user can upload an image to transform. For the file uploader, we can use Filestack’s new file picker V3.

Here, pick now returns a promise the way modern Javascript works so my implementation takes advantage of ES2017 async/await. Take a look at the code:

filestack = () => {
  return client.pick(
    {
      accept: 'image/*',
      maxSize: 1024 * 1024 * 2,
      transformOptions: {
        transformations: {
          rotate: true,
          circle: true,
          monochrome: true,
          sepia: true,
          crop: {
            aspectRatio: 16 / 9,
          },
        },
      },
    }
  );
};

The pick function allows user to apply several image transformation within its UI right before uploading the photo. The total customization allows our clients to decide which ones to provide so in my case I chose them all.
Please note, there is a picture size limit, 2MBs.

Now that we have the promise from filestack, we need another function to handle the response when the promise either resolves or rejects right?
That’s handleClick job, this async function is the core function for the view:

Here is the code:

async handleClick () {
  try {
    const { filesUploaded } = await this.filestack();
    const handle = filesUploaded[0].handle;
    this.setState({ handle, transformation: this.setTransformation() });
  } catch (e) {
    console.log(e);
  }
}

Chaining Conversions

When we chain conversions, the API is able to combine several transformations in a variety of ways to produce different results. Simply, order does matter and the documentation provides a very simple example to show that.

Furthermore, it provides a general multiple task URL format

https://process.filestackapi.com/[task]=[options]/[task]=[options]/Filestack_FileLink_Handle

or

https://process.filestackapi.com//[task]=[options]/[task]=[options]/File_URL

every / separates a task with relative options.

I first mentioned monochrome and torn_edges so let’s apply these transformations on the following newspaper photograph:

The transformation URL will be

https://cdn.filestackcontent.com/torn_edges/monochrome/eBxw9nJBQWxVJX8e4PIA

which gives a retro feeling to the photo!

Here we are preparing the transformation URL and apply chaining.
To compress or sharpen a photo we trigger setTransformation whenever a user selects a transformation in the form.

We have just seen the function call in handleClick but the same is done in handleChange:

handleChange = () => {
  this.setState({ transformation: this.setTransformation() });
}

So here is the code for setTranformation:

setTransformation = () => {
  const { getCompress, getSharpen } = this;
  return filestackCDN + getSharpen() + getCompress();
}

For clarity I separated the 2 available transformations in specific functions getSharpen and getCompress.

getSharpen = () => {
  return `${this.sharpen.checked ? '/sharpen' : ''}`;
}
getCompress = () => {
  const { resize, resizeWidth } = this;
  return `${resize.checked
    ? `/resize=w:${resizeWidth.value}/compress`
    : '/compress'
  }`;
}

Both functions retrieves the form values and create the transformation URL.

Now, try to upload a photo, apply all the transformations take a look at the URL in the browser development tools:

In the example I chained all the available transformations!

More Image Transformations

Here is a complete list of image transformations supported by Filestack.

Compress
Image to Ascii
Facial Detection
Crop
Rotate
Border and Effects
Filters
Collage
Image Enhancements
URL Screenshot
Image to ASCII
File type conversions
Security

See you next time!

Exit mobile version