Transform images quickly and easily in your React app

Transform images quickly and easily in your React app

To integrate Cloudinary image transformations into your existing React project, take note of the following points. Install the React SDK. Include the required elements of the cloudinary-react library in your code. Set Cloudinary configuration parameters.

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.

Create React App Crash Course: Easily start a React app

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:

App.js

import { CloudinaryContext, Image, Transformation } from 'cloudinary-react';
  • 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:

  • App.js*

    <Image cloudName="demo" publicId="sample" width="300" crop="scale" />
  • Configuration with CloudinaryContext applies to all child elements:

  • App.js*

<CloudinaryContext cloudName="demo">
  <div>
    <Image publicId="sample" width="50" />
  </div>
  <Image publicId="sample" width="0.5" />
</CloudinaryContext>

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 … App.js

<Image publicId="sample" />

… is compiled by React to:

index.js

<img src="https://res.cloudinary.com/{cloud_name}/image/upload/sample" />

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.

App.js

<Image publicId="sample">
  <Transformation height="150" width="150" crop="fill" effect="sepia" radius="20" />
  <Transformation overlay="text:arial_60:This is my picture" gravity="north" y="20" />
  <Transformation angle="20" />
</Image>

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: App.js

<Image publicId="family.jpg" >
  <Transformation width="300" height="300" gravity="faces" crop="fill" />
</Image>

The original image has an original dimension of 1000x667

cloudinary image optimization

Photo created by Hart Tan from Tomato Photo

cloudinary responsive images 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 fetchFormatparameter
  • 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: App.js

<Image publicId="sample.gif" />

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

<Image publicId="flower.jpg" >
  <Transformation width="350" fetchFormat="auto" crop="scale" />
</Image>

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).

responsive image sizes Original photo by Prince Akachi on Unsplash

responsive image generator 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 fetchFormatand 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. App.js

<Image publicId="city.jpg" >
  <Transformation quality="auto" fetchFormat="auto" />
</Image>

cloudinary dynamic image

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 autovalue for the dprand width attributes. The auto value is replaced with actual values on the client-side based on the actual browser settings and window width:

App.js

<Image
  dpr="auto"
  responsive
  width="auto"
  crop="scale"
  publicId="sample"
  angle="30">
  <Transformation effect="cartoonify" />
  <Transformation border="3px_solid_rgb:00390b" radius="20" />
</Image>

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.

reactjs react javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Routing in React without React-Router

I have been using React JS in my projects for quite some time now and am used to managing routing in my app using the react-router package. I have always been keen on having as little dependencies in my apps as possible, so, I always felt perturbed by the use of this particular package in simpler apps which did not have complex routes.

Forms of Composition in JavaScript and React

One of the core ideas in functional programming is composition: building larger things from smaller things. The canonical example of this idea should be familiar with legos.

How to Setup React Router v5 using React Hooks

React Router library makes the navigation experience of the client in your web page application more joyful, but how?! React Router, indeed, prevent the page from being refreshed. Thus the blank page resulted from a refreshed page is not...

React Fundamentals - ENTERING REACT AFTER LEARNING JAVASCRIPT

After all my teachings about React, be it online for a larger audience or on-site for companies transitioning to web development and React.