Image Editing and Cropping in ReactJs

image editing cropping in reactjs

If you have an application where a profile section is created, you most probably also asking for user’s photo for it. But different users have different phones and you end up having uncertain photo sizes. To cater this situation, we need cropping functionality. In this article, we will quickly show you how you can add a cropping feature in your reactjs application.

Introduction

It is easy to include a component that easily edits, and crops images before an upload in a pre-existing application. A few steps are required to achieve all that in Reactjs. In a nutshell, the steps include:

Getting Started

Installing React-Image-Crop(npm package)

Execute the command below or add the package as a dependency to your application

npm i react-image-crop --save

OR

yarn add react-image-crop

Create a Simple Image Upload with the preview section

Here we include an input file component that allows images of all types such as png, jpg, and jpeg to be displayed for cropping and editing. This component is essentially important in applications that allow profile images and passport uploads.

Import the component in App.js

Once you have confirmed the image upload works, you can then proceed with creating the cropping functionality in the .jsx file. The react-crop-image npm package library comes in handy to add the component features. Once you are done, import the component to the main js file; in our case the App.js. Rerun the application and make sure every component is efficiently working. With that, Let’s get to the juicy part.

Code Example

//crop.jsx
import React, { useState } from "react";
import ReactCrop from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";

const Crop = () => {
  const [src, selectFile] = useState(null);
  const handleFileChange = (e) => {
    selectFile(URL.createObjectURL(e.target.files[0]));
  };

  const [setImage] = useState(null);
  const [crop, setCrop] = useState({ aspect: 16 / 9 });

  function getCroppedImg() {
    const canvas = document.getElementById("canvas");
    const image = document.getElementById("result");
    const ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    console.log(
      image.width,
      image.height,
      image.naturalWidth,
      image.naturalHeight
    );

    const imageWidthRatio = image.naturalWidth / image.width;
    const imageHeightRatio = image.naturalHeight / image.height;

    console.log(crop);
    ctx.drawImage(
      image,
      crop.x * imageWidthRatio,
      crop.y * imageHeightRatio,
      crop.width * imageWidthRatio,
      crop.height * imageHeightRatio,
      0,
      0,
      crop.width,
      crop.height
    );
  }
  return (
    <div className="container">
      <div className="row">
        <div className="col-6">
          <input type="file" accept="image/*" onChange={handleFileChange} />
        </div>
        {src && (
          <div>
            <ReactCrop crop={crop} onChange={setCrop}>
              <img id="result" src={src} alt="description" onLoad={setImage} />
            </ReactCrop>
            <button className="btn btn-danger" onClick={getCroppedImg}>
              Crop image
            </button>
          </div>
        )}
        <canvas
          id="canvas"
          width={crop.width}
          height={crop.height}
          style={{
            border: "1px solid black",
            objectFit: "contain"
          }}
        ></canvas>
      </div>
    </div>
  );
};
export default Crop;
//App.js

import React from "react";
import Crop from "./crop";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Crop />

      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

From the code snippet crop.jsx above, we:

In the cropping operation:

Save the changes and open up the browser to test out the ImageCropper component.

      This is the best article on image cropping in ReactJs ♥♥

Click here to Tweet this

Live Demo

Open Live Demo