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:
- Installing React-Image-Crop (npm package)
- Create a Simple Image Upload with the preview section
- Import the component in App.js
- Rerun the application
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:
- Imported and used
ReactCrop
from thereact-image-crop
package installed earlier. - Used an
input
tag to allow the user to select a file for cropping. - Defined some default arguments such as
aspect
,height
,unit
,width
, etc. which we will use in the image cropping and reconstruction process. - We also created some functions which included
handleFileChange
accepting files. With the help of theFileReader
method, we loaded the image to theReactCrop
component for cropping.
In the cropping operation:
- Created the
imageLoaded
function to load and get the image ready for cropping. - We also created the
crop
function that accepts the crop dimensions, which are calculated by adjusting the cropping lines shown on the screen. - Once the user sets the crop dimensions, the
getCroppedImg
function receives the new image data (filename, crop, and image) and it is used to reconstruct the final image for upload. The process is achieved using a2D canvas
which is used to generate, manipulate and render graphical elements in React.js. - The cropped image is drawn to scale with the dimensions and image meta-data provided in the canvas. The image is now ready for display.
Save the changes and open up the browser to test out the ImageCropper
component.