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:
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;
    1. Create variables that use the cld instance with the Public ID of the images to generate the image URLs:

 

const imageToCropToSpecifiedDimension = cld.image("store");
const imageToCropToThumbnail = cld.image("man");
const imageToCropWithImagga = cld.image("beach");
  1. 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());
    

     

  2. In the return (); function, add the JSX to display the images on the browser using the Cloudinary AdvancedImage component:
  3. <>
      <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

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better implement and optimize image cropping in React applications:

  1. Use server-side cropping for performance optimization
    Always prefer server-side cropping to reduce payload size. Rather than delivering the entire image and using CSS for client-side cropping, utilize tools like Cloudinary to serve cropped images directly from the server. This approach minimizes bandwidth, speeds up page load times, and improves overall user experience.
  2. Choose the right crop mode for different contexts
    Different crop modes serve specific purposes. Use:

    • crop for exact dimensions when layout precision is critical.
    • thumb for generating profile images or small thumbnails focused on a particular subject.
    • imaggaCrop for intelligently cropping around key visual elements using AI.

    Select the appropriate mode based on the context and content of your images.

  3. Use focal points for better visual emphasis
    When dealing with complex images (e.g., group photos or scenes with multiple subjects), manually define focal points to ensure that key areas remain in the frame. This is particularly useful when face detection might not capture the most relevant visual information.
  4. Implement responsive cropping for multi-device support
    Use responsive cropping techniques to generate multiple versions of images for different screen sizes and device types. Tools like Cloudinary’s responsive breakpoints enable you to crop and resize images dynamically based on screen dimensions, ensuring that each device receives an optimized version.
  5. Leverage smart cropping for dynamic content
    Use AI-based smart cropping techniques for dynamically changing content, like news sites or social media feeds, where the focal point may vary across images. Smart cropping analyzes the content and context, producing crops that maintain visual balance without manual intervention.
  6. Combine face and content-aware cropping for people-focused images
    For images containing people, combine face detection and content-aware cropping to keep faces centered while preserving context. This hybrid approach is ideal for team photos, headshots, or images with mixed content (e.g., person and scenery) to ensure a balanced crop.
  7. Optimize image delivery for varying resolutions
    Always deliver different image sizes based on device resolution and network speed. Use Cloudinary’s dpr_auto and quality_auto settings to automatically adapt images to high-resolution displays (e.g., Retina) or slower networks, enhancing both visual quality and performance.
  8. Test cropping configurations with varied content types
    Run tests using different cropping configurations to verify how they handle diverse content types (e.g., portraits, landscapes, product shots). This testing ensures that your cropping strategy works across all types of visuals, preventing critical content from being cut off or misaligned.
  9. Use Cloudinary’s transformations to fine-tune crops
    Cloudinary offers powerful transformation options beyond basic cropping. Combine transformations like round_corners for circular thumbnails, overlay for adding watermarks, or background_removal to isolate subjects before cropping. These advanced techniques create visually appealing and customized images.
  10. Integrate caching strategies for frequently cropped images
    If you have frequently accessed images that undergo similar cropping patterns, implement caching strategies to store these cropped versions. This reduces the need to generate new transformations for repeat requests, saving on processing time and API costs.

By applying these advanced tips, you can fully leverage image cropping in your React applications, ensuring that your visuals are optimized, responsive, and visually engaging across various use cases and devices.

Last updated: Oct 3, 2024