Open In App

How to crop images in ReactJS ?

Last Updated : 24 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Image cropping is a common requirement in web applications, especially when dealing with user-generated content, photo editing, or image manipulation. ReactJS, being a popular JavaScript library for building user interfaces, provides various techniques and libraries that can be used to implement image cropping functionality. In this article, we’ll explore react-image-crop package to achieve so.

The react-image-crop is a tool for cropping images for React with no dependencies. This tool will help us in cropping images, It takes an image as a source, and after selecting the target area it will provide us with the cropped dimensions.

Approach: In order to crop the image, we have used the react-image-crop module, which is very popular for cropping images. We have imported that module and used the ReactCrop component from this package. In our main App.js file, we have used this component and passed it as a child to our input element which chooses files. 

Creating React Application And Installing Module:

Step 1: Create a React app using the following command:

npx create-react-app demo

Step 2: After creating your project folder i.e. demo, move to it using the following command:

cd demo

Project structure: Our project structure will look like this.

Step 3: After creating the ReactJS application, Install the react-image-crop package using the following command:

npm install react-image-crop

Implementation: Write down the following code in respective files.

App.js

Javascript




import { useState } from 'react';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
 
function App() {
    const [src, setSrc] = useState(null);
    const [crop, setCrop] = useState({ aspect: 16 / 9 });
    const [image, setImage] = useState(null);
    const [output, setOutput] = useState(null);
 
    const selectImage = (file) => {
        setSrc(URL.createObjectURL(file));
    };
 
    const cropImageNow = () => {
        const canvas = document.createElement('canvas');
        const scaleX = image.naturalWidth / image.width;
        const scaleY = image.naturalHeight / image.height;
        canvas.width = crop.width;
        canvas.height = crop.height;
        const ctx = canvas.getContext('2d');
 
        const pixelRatio = window.devicePixelRatio;
        canvas.width = crop.width * pixelRatio;
        canvas.height = crop.height * pixelRatio;
        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,
            crop.height,
        );
 
        // Converting to base64
        const base64Image = canvas.toDataURL('image/jpeg');
        setOutput(base64Image);
    };
 
    return (
        <div className="App">
            <center>
                <input
                    type="file"
                    accept="image/*"
                    onChange={(e) => {
                        selectImage(e.target.files[0]);
                    }}
                />
                <br />
                <br />
                <div>
                    {src && (
                        <div>
                            <ReactCrop src={src} onImageLoaded={setImage}
                                crop={crop} onChange={setCrop} />
                            <br />
                            <button onClick={cropImageNow}>Crop</button>
                            <br />
                            <br />
                        </div>
                    )}
                </div>
                <div>{output && <img src={output} />}</div>
            </center>
        </div>
    );
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Reference: https://www.npmjs.com/package/react-image-crop



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads