React resize, crop & compress images before upload; In this tutorial, you will learn how to use ReactJS to resize, crop, and compress images before uploading them to your server. This will be useful if you need to reduce the size of images to save storage space or if you want to improve the user experience by reducing the upload time.
You will be using the ReactJS library, along with the popular image processing library called CropperJS. We will also use the HTML5 canvas element to resize the image.
Before you begin, make sure you have the following:
- Basic knowledge of ReactJS and JavaScript
- Node.js and npm installed on your computer
- A text editor such as VS Code or Sublime Text
How to Resize Image Before Upload in React js
Follow the following steps and resize, crop, and compress images before uploading in react js app:
- Step 1 – Create React App
- Step 2 – Install React Image Crop Package
- Step 3 – Create the Image Upload Component
- Step 4 – Test the Image Upload Component
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
Execute the following command to install react image crop dependencies into your react app:
npm install cropperjs canvas --save
CropperJS is a JavaScript library for cropping images, and it provides several methods for working with the cropped image as a canvas element. Here are some of the main canvas-related methods provided by CropperJS:
getCroppedCanvas()
: This method returns a canvas element that contains the cropped portion of the original image. You can specify options such as the output size, format, and quality of the cropped canvas.getCroppedCanvas(options)
: This method allows you to specify additional options for the cropped canvas, such as the output type (jpeg
orpng
), the output quality (0 to 1), and whether to include the original image’s metadata in the output.setCanvasData(data)
: This method sets the data for the canvas element. Thedata
parameter should be an object that contains the following properties:left
,top
,width
,height
,naturalWidth
, andnaturalHeight
.setCropBoxData(data)
: This method sets the data for the crop box. Thedata
parameter should be an object that contains the following properties:left
,top
,width
, andheight
.clear()
: This method clears the canvas element.replace(url)
: This method replaces the current image with a new image specified by theurl
parameter. The canvas element is updated with the new image.disable()
: This method disables the cropping functionality of the CropperJS instance.enable()
: This method enables the cropping functionality of the CropperJS instance.
By using these methods, you can manipulate the canvas element generated by CropperJS in various ways, such as setting its dimensions, exporting it as an image, or replacing the original image with a new one.
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;
Here’s a summary of the ImageUpload.js
component code:
- Import the
React
anduseState
hooks from thereact
library, and import theCropper
class and its stylesheet from thecropperjs
library. - Define a functional component called
ImageUpload
that renders an input element of type “file” and a CropperJS instance. - In the component’s state, define a
image
variable that will store the selected image, and acropper
variable that will store the instance of the CropperJS class. - Define a function called
handleFileInputChange
that is called when the user selects an image file. This function reads the file using theFileReader
API and sets theimage
state variable to the result. - Define a function called
handleCrop
that is called when the user clicks the “Crop” button. This function gets a cropped canvas using thegetCroppedCanvas
method of thecropper
instance, and then converts the canvas to a Blob using thetoBlob
method. The Blob is then logged to the console. - Return JSX that renders the file input element, the CropperJS instance, and a “Crop” button. The CropperJS instance is configured with several options that control its behavior, such as the initial aspect ratio, whether to show guides, and the minimum crop box size. The
onInitialized
callback is used to set thecropper
state variable to the instance of the CropperJS class. - Export the
ImageUpload
component as the default export of the module.
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 ReactJS along with the CropperJS library to resize, crop, and compress images before uploading them to a server. We used the HTML5 canvas element to resize the image and the toBlob
method to compress it.
By following the steps in this tutorial, you can create an image upload component in your ReactJS application that provides a better user experience by reducing the upload time and the storage space required for the images.
Of course, there are many other ways to implement image uploading in a ReactJS application, and this tutorial is just one example. I hope this tutorial has been helpful in showing you one way to accomplish this task, and that you can build upon this example to create a solution that meets your specific needs.
How to compress it ?