React Js Image File Crop and Resize Example Tutorial

Image cropping is the process of changing or shrinking the size of the image; if you do not know how to resize an image using the cropping method, then this tutorial is for you.

In this tutorial, you will find out how to create an image crop component in React application. We will use the powerful react-image-crop library to crop the image in react app.

As we know, larger files consume more bandwidth than smaller files. As a result, it costs you more money. This guide aims to solve the image size problem and provides your users the functionality to resize the image size.

How to Resize and Crop Image in React

Here are the bit-by-bit steps that are going to teach you how to use the react image size package in react.

  • Step 1: Create React Project
  • Step 2: Install React Image Crop Library
  • Step 3: Build Image Crop Component
  • Step 4: Register Image Crop Component
  • Step 5: Test React Application

Create React Project

First step is to install the new React application with the given command.

npx create-react-app xost

Move into the app folder.

cd xost

Install React Image Crop Library

Secondly, you have to install the react-image-crop library, you may use the given command.

npm install react-image-crop

Build Image Crop Component

You have to use the ReactCrop tag to show the image crop component, define the src, crop, and other essential properties that will help you resize the image.

So, let us create the components/ folder, after that create Crop.js inside the components folder.

Update the code in components/Crop.js.

import React from 'react';

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



export default class Crop extends React.Component {
    state = {
        src: null,
        crop: {
          unit: '%',
          width: 30,
          aspect: 16 / 9
        }
      };
    
      onImgChange = (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]);
        }
      };
    
      onFileLoaded = (image) => {
        this.imageRef = image;
      };
    
      onImgCropComp = (crop) => {
        this.makeClientCrop(crop);
      };
    
      onImgCropChange = (crop, percentCrop) => {
        this.setState({ crop });
      };
    
      async makeClientCrop(crop) {
        if (this.imageRef && crop.width && crop.height) {
          const imgPath = await this.getResizeImage(
            this.imageRef,
            crop,
            'newFile.jpeg'
          );
          this.setState({ imgPath });
        }
      }
    
      getResizeImage(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, imgPath, src } = this.state;
    
        return (
          <div className="App">
            <div>
              <input type="file" accept="image/*" onChange={this.onImgChange} />
            </div>
            {src && (
              <ReactCrop
                src={src}
                ruleOfThirds
                crop={crop}
                onImageLoaded={this.onFileLoaded}
                onChange={this.onImgCropChange}
                onComplete={this.onImgCropComp}
              />
            )}
            {imgPath && (
              <img alt="Crop" style={{ maxWidth: '400px' }} src={imgPath} />
            )}
          </div>
        );
      }
}

Register Image Crop Component in App Js

Head over to the App.js file, then import the Crop component at the top, also define the Crop tag inside the App function.

import React from "react";
import './App.css';
import Crop from "./components/Crop";


export default function App() {
  return (
    <Crop />
  );
}

Test React Application

Now, you have to start the React application, make sure to use the given command and run the app.

npm start

React Js Image File Crop and Resize Example Tutorial

Summary

In this informational guide, we learned how to build an image crop feature using the react-image-crop plugin.

Also, how to implement image resizer feature in the React class component, how to play around the state, crop properties, and crucial events that deal with image resizing in React.