In this tutorial, you will learn how to resize, crop, and compress images before uploading them to your server in react js applications using cropper js.
How to Resize Image Before Upload in React js
Steps to resize, crop, and compress images before uploading:
Step 1 – Create React App
In this step, open your terminal and execute the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install React Image Crop Package
Run the following command to install react image crop dependencies into your react app:
npm install cropperjs canvas --save
Step 3 – Create the Image Upload Component
Now, let’s create a new component that will allow users to upload an image.
In your project’s src
directory, create a new file called ImageUpload.js
and add the following code:
import React, { useState } from 'react'; import Cropper from 'cropperjs'; import 'cropperjs/dist/cropper.css'; const ImageUpload = () => { const [image, setImage] = useState(null); const [cropper, setCropper] = useState(null); const handleFileInputChange = (e) => { e.preventDefault(); const fileReader = new FileReader(); fileReader.onload = () => { setImage(fileReader.result); }; fileReader.readAsDataURL(e.target.files[0]); }; const handleCrop = () => { const canvas = cropper.getCroppedCanvas(); canvas.toBlob((blob) => { console.log(blob); }); }; return ( <div> <input type="file" onChange={handleFileInputChange} /> {image && ( <Cropper src={image} initialAspectRatio={1} guides={false} viewMode={1} minCropBoxWidth={200} minCropBoxHeight={200} background={false} responsive={true} autoCropArea={1} checkOrientation={false} onInitialized={(instance) => { setCropper(instance); }} /> )} <button onClick={handleCrop}>Crop</button> </div> ); }; export default ImageUpload;
Step 4 – Test the Image Upload Component
To test the component, let’s add it to our App.js
file.
In your project’s src
directory, open the App.js
file and replace the existing code with the following:
import React from 'react'; import ImageUpload from './ImageUpload'; const App = () => { return ( <div> <ImageUpload /> </div> ); }; export default App;
Save the file and start the development server by running the following command in your terminal:
npm start
Now, open your web browser and navigate to http://localhost:300
Conclusion
In this tutorial, you learned how to use CropperJS library to resize, crop, and compress images before uploading them to a server in react js applications.
How to compress it ?