React 18 Resize, Compress and Crop Image Size Tutorial

Last Updated on by in React JS

React js image resize tutorial; In this quick guide, we will learn how to crop an image in React js app using the react image crop package.

Image cropping is the process of resizing the image after selecting from the input select HTML form element.

We will show you how to set or update the height and width of an image in react js after upload, and we will primarily crop the image in react app.

For accomplishing this task, we will use react image crop library.

It is a powerful plugin and an image cropping tool for React that requires no dependencies, offers responsiveness, is touch-enabled, does fixed-aspect crops, supports min and max crop size.

All in all, it is a very useful and helpful plugin for resizing the image in react js.

How to Crop Image Size in React Js App

  • Step 1: Set Up New React App
  • Step 2: Add React Image Crop Package
  • Step 3: Implement Image Resizing in React
  • Step 4: Update App Js File
  • Step 5: Start React App

Set Up New React App

Begin the first step with installing the new react application using the “npx create” react cli command.

npx create-react-app react-blog

App has been created, next, go inside the project.

cd react-blog

Add React Image Crop Package

Now, you require to install the React Image Crop package in react js application with the help of the given below command.

npm install react-image-crop --legacy-peer-deps

Implement Image Resizing in React

To integrate the image crop in react native, you have to create the components/ folder and the ImageResize.js file.

Now, import the ReactCrop module from the ‘react-image-crop’ package also import the react crop CSS. Conjugate all the functions and methods within the ImageResize class to add the image cropping functionality.

import React from 'react';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';


class ImageResize extends React.Component {
    state = {
        src: null,
        crop: {
          unit: '%',
          width: 20,
          aspect: 16 / 9
        }
      };
    
      onFileChange = (e) => {
        if (e.target.files && e.target.files.length > 0) {
          const reader = new FileReader();
          reader.addEventListener('load', () =>
            this.setState({ src: reader.result })
          );
          reader.readAsDataURL(e.target.files[0]);
        }
      };
    
      // If you setState the crop in here you should return false.
      onImageLoaded = (image) => {
        this.imageRef = image;
      };
    
      onCropComplete = (crop) => {
        this.makeClientCrop(crop);
      };
    
      onCropChange = (crop, percentCrop) => {
        // You could also use percentCrop:
        // this.setState({ crop: percentCrop });
        this.setState({ crop });
      };
    
      async makeClientCrop(crop) {
        if (this.imageRef && crop.width && crop.height) {
          const croppedImageUrl = await this.getCroppedImg(
            this.imageRef,
            crop,
            'newFile.jpeg'
          );
          this.setState({ croppedImageUrl });
        }
      }
    
      getCroppedImg(image, crop, fileName) {
        const canvas = document.createElement('canvas');
        const pixelRatio = window.devicePixelRatio;
        const scaleX = image.naturalWidth / image.width;
        const scaleY = image.naturalHeight / image.height;
        const ctx = canvas.getContext('2d');
    
        canvas.width = crop.width * pixelRatio * scaleX;
        canvas.height = crop.height * pixelRatio * scaleY;
    
        ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
        ctx.imageSmoothingQuality = 'high';
    
        ctx.drawImage(
          image,
          crop.x * scaleX,
          crop.y * scaleY,
          crop.width * scaleX,
          crop.height * scaleY,
          0,
          0,
          crop.width * scaleX,
          crop.height * scaleY
        );
    
        return new Promise((resolve, reject) => {
          canvas.toBlob(
            (blob) => {
              if (!blob) {
                //reject(new Error('Canvas is empty'));
                console.error('Canvas is empty');
                return;
              }
              blob.name = fileName;
              window.URL.revokeObjectURL(this.fileUrl);
              this.fileUrl = window.URL.createObjectURL(blob);
              resolve(this.fileUrl);
            },
            'image/jpeg',
            1
          );
        });
      }
    
      render() {
        const { crop, croppedImageUrl, src } = this.state;
    
        return (
          <div className="App">
            <div>
              <input type="file" accept="image/*" onChange={this.onFileChange} />
            </div>
            {src && (
              <ReactCrop
                src={src}
                crop={crop}
                ruleOfThirds
                onImageLoaded={this.onImageLoaded}
                onComplete={this.onCropComplete}
                onChange={this.onCropChange}
              />
            )}
            {croppedImageUrl && (
              <img alt="Crop" style={{ maxWidth: '100%' }} src={croppedImageUrl} />
            )}
          </div>
        );
      }
}


export default ImageResize;

Update App Js File

Next, import the ImageResize from ‘./components/ImageResize’ and add the ImageResize component in the App function.

Open src/App.js and update the following code inside the file.

import React from 'react';
import './App.css';

import ImageResize from './components/ImageResize';

function App() {
  return (
    <div className="App">
      <ImageResize />
    </div>
  );
}

export default App;

Start React App

In the final step, we need to invoke the development server using the npm start command, so go ahead and evoke the following command.

npm start

After starting the development server, you may see the app on the browser:

http://localhost:3000

React Js Resize, Compress and Crop Image Size Tutorial

Conclusion

In this stalwart tutorial, we profoundly learned how to create the image resize component for cropping and resizing the image size in react js application using the third party package called react image resize.