How to Crop an Image with React

crop image react

When building web applications, developers do their best to make all content responsive. A common way to perform this is by delivering full-size images and relying on browser-side cropping (CSS and HTML width and height attributes). However, this forces visitors to download the original large image files before serving the cropped image.

React, a JavaScript library for building user interfaces, offers many cropping packages. However, these still don’t solve the problem of forcing visitors to download large image files before serving the cropped images. The best way to solve this problem is to deliver images from the server at their final size needed for responsiveness on the users’ device, window size, or resolution.

Automatically resize and crop image with AI

This article will discuss how to dynamically crop images on the fly. The magic of Cloudinary and its image transformation features to deliver image assets to the browser at the requested size.

Sandbox

We’ve completed this project in a CodeSandbox. Fork and run it to quickly get started to crop an image with React.

    <CodeSandbox id="lucid-goldwasser-9qm7rk" title="How to crop an image with React" />

The GitHub link is here.

Using Cloudinary in a React application

Cloudinary is an end-to-end media management platform for software applications covering everything from uploads, storage, transformations and optimizations to delivery. Cloudinary offers SDKs for frontend, backend, and mobile development.

One of the cool features of Cloudinary is its ability to transform media on-the-fly, meaning, there’s no need to pre-process images and videos. Instead, simply append attributes to the URL and Cloudinary will go off to generate that asset and return it.

To use Cloudinary:

  1. Set up an account — create one for free here.
  2. Configure the React SDK.
  3. Upload the images you want to crop. 
  4. Crop using Cloudinary’s cropping modes.

    4 steps process upload media

Configuring Cloudinary in a React application

After creating a free Cloudinary account, build a React application by navigating to a directory and running the command below in a terminal:

    npx create-react-app crop_image && cd crop_image

The above command creates a React application called ‘crop_image’ and navigates to the project directory.

Next, install the @cloudinary/url-gen and @cloudinary/react packages with:

npm i @cloudinary/url-gen @cloudinary/react

The @cloudinary/url-gen package contains all the functionalities required to create delivery URLs for uploaded images.

The @cloudinary/react package contains the React components for rendering, configuring, and transforming the images.

Include the Cloudinary account Cloud Name as an environment variable. You get the Cloud Name by logging into the Cloudinary console and viewing any of the highlighted sections as shown below:

Cloudinary dashboard image

Then, create a .env file in the root directory and add the variable below to the file:

REACT_APP_CLOUDINARY_CLOUD_NAME=/*YOUR CLOUD NAME HERE/*

Lastly, upload the images you want to crop to your Cloudinary account. 

Uploading images to Cloudinary

There are multiple ways to upload images to Cloudinary. For this article, we will use the Cloudinary Upload widget.

To upload images using the Upload widget on the Cloudinary console, click on Media Library and then Upload:

Media Library Cloudinary Selection

In the popup, select the Web Address option to upload an image via a web url:

Public URL file to upload web assets

Here are 3 sample images we can use:

It’s time to start cropping!

  • Crop the store image to a specific dimension using the crop mode.
  • Crop the man image to thumbnail with face detection using the thumb mode
  • Crop the beach image smartly without scaling it using the Cloudinary Imagga add-on.

Using Cloudinary cropping modes in React

  1. Import the Cloudinary packages and the required actions and qualifiers to use the cropping modes and to crop an image with React. Then instantiate Cloudinary and pass a cloud name (the unique identifier name for your Cloudinary product environment. You can find it on the top right side of the Cloudinary dashboard).
  2. Update the src/App.js file of the React application:
  3. import { Cloudinary } from "@cloudinary/url-gen";
    

    import {AdvancedImage} from "@cloudinary/react";

    // Import required actions and qualifiers
    import { crop, thumbnail, imaggaCrop } from "@cloudinary/url-gen/actions/resize";
    import {focusOn} from "@cloudinary/url-gen/qualifiers/gravity";
    

    import {face} from "@cloudinary/url-gen/qualifiers/focusOn";

    const App = () => {
      const cld = new Cloudinary({
        cloud: {
          cloudName: process.env.REACT_APP_CLOUDINARY_CLOUD_NAME
        }
      });
    
    
      return (
      );
    }
    export default App;
    
  4. Create variables that use the cld instance with the Public ID of the images to generate the image URLs:
  5. const imageToCropToSpecifiedDimension = cld.image("store");
    const imageToCropToThumbnail = cld.image("man");
    const imageToCropWithImagga = cld.image("beach");
    
  6. Crop the images using the imported Cloudinary qualifiers and actions:

    //Cropping to a specficed dimension of 300px by 300px
    imageToCropToSpecifiedDimension.resize(crop().width(300).height(300));
    

    // Cropping to thumbnail with focus on face
    imageToCropToThumbnail.resize(
      thumbnail()
        .width(300)
        .height(300)
        .gravity(focusOn(face()))
    );
    

    // Using the Imagga addon to smartly crop
    imageToCropWithImagga.resize(imaggaCrop());
    

  7. In the return (); function, add the JSX to display the images on the browser using the Cloudinary AdvancedImage component: 
  8. <>
      <div>
        <h2>Crop To Specified Dimension</h2>
        <AdvancedImage cldImg={imageToCropToSpecifiedDimension} />
      </div>
      <br />
      <div>
        <h2>Thumbnail Crop</h2>
        <AdvancedImage cldImg={imageToCropToThumbnail} />
      </div>
      <br />
      <br />
      <div>
        <h2>Imagga Crop</h2>
        <AdvancedImage cldImg={imageToCropWithImagga} />
      </div>
    </>
    

    The AdvancedImage component creates an image by passing the generated image URL (the image variables).

    The results

    The store image before cropping:

    Store image before cropping

    The store image after cropping:

     

    The man image before cropping:

    Man image before cropping

    The man image after cropping:

    Man image after cropping

    The beach image before cropping:

    Beach image before cropping

    The beach image after cropping:

    Beach image after cropping

    Conclusion

    You’ve seen how easy it is to crop an image using Cloudinary and React. Additionally, Cloudinary offers advanced media functionality like filtering, resizing, retouching, and more. Try it out (it’s free forever!) and unleash the full potential of your digital media.

    More from Cloudinary

Last updated: Dec 26, 2023