Speedy Image Transformation in React.js Using Cloudinary

Transform images quickly and easily in your React app

Idris Olamide Ganiyu
Better Programming
Published in
8 min readNov 1, 2019

--

Photo by Rodion Kutsaev on Unsplash

Introduction

Images are a very common and important element of modern web applications and, as such, need to be properly manipulated to fit the design of your application. This post teaches you how Cloudinary image manipulations and transformations work, provides detailed descriptions, and also showcases use‑case examples for commonly used transformations.

Cloudinary allows you to easily transform images on the fly to any required or suitable format, style, and dimension. It also delivers optimized images with minimal file size while maintaining high visual quality for a great user experience — even with minimal bandwidth.

All these can be done by implementing dynamic image transformation and delivery URLs. You can also change the required transformations at any time. All the transformed images are created on-demand (lazily) and delivered to the end users through a fast CDN with optimized caching.

Cloudinary

Cloudinary, a cloud provider for media management, provides a variety of options for image transformations.

For example, you can resize and crop images. Then you can deliver them using the image format that fits your needs while also applying a variety of filters and effects.

You can also use Cloudinary’s smart-cropping techniques, which include face detection or auto-gravity for cropping based on the most relevant parts of uploaded photos. For complex transformations, you can use the management console or admin API for defining named transformations and even run a set of chained transformations on your images. You can also use the management console to view your delivery usage reports and optimization insights.

To use all these aforementioned features, it is essential to have a Cloudinary account.

Creating a Cloudinary Account

To upload images that’ll be transformed and delivered to your web applications, a Cloudinary account is essential. To create one, log on at https://www.cloudinary.com, and follow the following steps:

  • Click the Sign Up button
  • Fill in the fields with the appropriate information
  • Edit the cloud name to your preferred one, and tick the captcha box for verification
  • Submit the Sign Up form by clicking the Create Account button
  • After the welcome modal pops up, select the appropriate fields, and proceed

Uploading an Image

Images can be uploaded in a variety of ways. You could drag and drop them from your local computer or browse to the image itself. Additional options include the use of an URL address, social media links, a Dropbox address, and a Google image address.

  • In the dashboard, select the Media Library tab.
  • Select the Upload Media option.
  • Select the Advanced option, and input a unique name for the image’s public ID. The public ID is the unique identifier of the image.
  • Select a convenient video upload option: In this case, the drag-and-drop option was used to get the video — as it is available locally.

The image will be automatically uploaded to the Cloudinary servers after the completion of the last step.

Note these parameters: cloudname and publicId. The cloudname is the unique name of the user when opening a Cloudinary account. This is needed to assess the user’s uploaded images on Cloudinary, while the publicId parameter is the unique identifier of the user’s uploaded image.

Using ReactJS

To integrate image transformation using React, Cloudinary specifies its React SDK which easily performs smart image manipulations using code that integrates seamlessly with your existing React application and delivers optimized and responsive media to your users.

React SDK features

  • Build URLs for image and video transformation and manipulation
  • Helper elements for embedding and transforming images — and more

React capitalization and data-type guidelines

According to the official documentation of Cloudinary, it’s important to keep the following guidelines in mind when using the React SDK:

  • Parameter names: camelCase. For example, publicId.
  • Classes: PascalCase. For example, ImageTag.
  • Methods: camelCase. For example, toHTML.
  • Pass parameter data as object

Installation and Setup

To integrate Cloudinary image transformations into your existing React project, take note of the following points.

1. Install the React SDK

The Cloudinary React SDK serves as a layer on top of the Cloudinary’s JavaScript (cloudinary-core) library. Install the SDKs by running the following command:

npm install cloudinary-react --save

2. Include the required elements of the cloudinary-react library in your code

The following three elements are needed for image transformation:

  • CloudinaryContext — allows you to define shared parameters that are applied to all child elements
  • Image — defines a Cloudinary image tag
  • Transformation — allows you to define additional transformations on the parent element

3. Set Cloudinary configuration parameters

To use the Cloudinary React elements, you must configure at least your Cloudinary account cloud name. You can additionally define several optional configuration parameters, if relevant. Y

ou can find your account-specific configuration credentials in the dashboard of your management console. You can apply these settings directly to each element, or you can apply them to all child elements using a CloudinaryContext element.

For example:

  • Configuration directly in the element:
  • Configuration with CloudinaryContext applies to all child elements:

React Image Manipulations

Your uploaded image assets to Cloudinary can be delivered to web applications via dynamic URLs. You can include instructions in the dynamic URLs which tell Cloudinary to manipulate the image assets using a set of transformation parameters.

All manipulations are performed automatically in the cloud, and the transformed assets are also automatically optimized before they are routed through a fast CDN to the end user for optimal user experience.

For example, you can resize and crop, add overlay images, blur or pixelate faces, apply a large variety of special effects and filters, and apply settings to optimize your images and deliver them responsively.

Cloudinary’s React library simplifies the generation of transformation URLs for easy embedding of assets in your React application.

Delivering and Transforming Images

Uploaded images can be delivered using the Image component. The output is a complete HTML <img> tag whose src points to the relevant Cloudinary transformation URL.

For example …

… is compiled by React to:

You can also add optional Transformation elements that’ll be used as chained transformations (each transformation is applied to the result of the previous transformation).

For example, the following code crops the image to “150x150”, rounds the corners, applies a sepia effect, adds text to the top center of the resized image, and then rotates the entire result by 20 degrees.

Applying Common Image Transformations Using React

Resizing and cropping

There are a variety of different ways to resize and/or crop your images and to control the area of the image that’s preserved during a crop.

The following example uses the fill cropping method to generate and deliver an image that fills the requested 300x300 size. It uses face detection gravity to ensure all the faces in the image are retained and centered when the image is cropped:

The original image has an original dimension of 1000x667

Photo created by Hart Tan from Tomato Photo
Optimized image (300 x 300) with gravity on faces and fill cropping

Converting to another image format

You can deliver any image uploaded to Cloudinary in essentially any image format. There are three main ways to convert and deliver in another format:

  • Specifying the image’s public ID with the desired extension
  • Explicitly set the desired format using the fetchFormat parameter
  • Use the value auto to instruct Cloudinary to deliver the image in the most optimized format for each browser that requests it.

For example:

Deliver a .jpg file in .gif format:

The following code lets Cloudinary select the optimal format for each browser. For example, in Chrome, this image delivers in .webp format.

Applying image effects and filters

There is a large selection of image effects, enhancements, and filters to be selected that can be applied to your images.

Available effects in Cloudinary include a variety of color-balance and level effects, tinting, blurring, pixelating, sharpening, automatic-improvement effects, artistic filters, image and text overlays, distortion and shape-changing effects, outlines, backgrounds, shadows, and more.

For example, the code below applies a cartoony effect, rounding corners effect, and background-color effect (and then scales the image down to a height of 300 pixels).

Original photo by Prince Akachi on Unsplash
Transformed Image

Image optimizations

Cloudinary, by default, automatically performs certain optimizations on all transformed images. However, there exist several additional features that enable you to further optimize the images for use in your React application. These include optimizations to the image quality, format, and size, among others.

For example, you can use the auto value for the fetchFormat and quality attributes to automatically deliver the image in the format and quality that minimizes file size while also meeting the required quality level.

Below, these two parameters are applied, resulting in an almost 50% file-size reduction (286KB vs. 151KB) with no visible change in quality.

An almost 50% file-size optimization using auto-format and auto-quality features. Original photo by Andrea Cau on Unsplash.

For an in-depth review of the many ways you can optimize your images, see Cloudinary’s image optimization documentation

Responsive image settings

Responsive web design is an approach to web-page creation that makes use of flexible layouts, flexible images, and cascading style sheet media queries to provide an optimal viewing experience irrespective of screen size and orientation.

The goal of responsive design is to build web pages that detect the visitor’s screen size and orientation and change the layout accordingly.

Ensuring that optimal experience means you should avoid sending high-resolution images that get resized client-side, with significant bandwidth waste for users of small displays. Instead, you should always deliver the right size image for each device and screen size.

Cloudinary can help reduce the complexity with dynamic image transformations. You can simply build image URLs with any image width or height based on the specific device resolution and window size. This means you don’t have to recreate the images — dynamic resizing takes place on the fly, as needed.

For example, you can ensure each user receives images at the size and device pixel ratio (DPR) that fits their device using the auto value for the dpr and width attributes. The auto value is replaced with actual values on the client-side based on the actual browser settings and window width:

Conclusion

In this article, we have discussed various ways by which images can be transformed using Cloudinary for better and optimal application and site performance.

However, there exists a lot of other transformation effects and methods that couldn’t be discussed in this article that can be viewed here.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Idris Olamide Ganiyu
Idris Olamide Ganiyu

Written by Idris Olamide Ganiyu

Front-end Developer and Technical Writer

No responses yet

Write a response