React js Resize, Crop, Compress Image Before Upload Tutorial

1. Install React-Image-Crop

The first step is to install the React-Image-Crop library. To do this, open a terminal window and run the following command:

npm install react-image-crop

2. Import React-Image-Crop

Once the library is installed, you can import it into your React component. To do this, add the following line of code to the top of your component file:

import ReactCrop from ‘react-image-crop’;

3. Add an Image

Next, you’ll need to add an image to your component. To do this, you can use the standard HTML tag. For example:

My Image

4. Add React-Image-Crop

Now that you have an image in your component, you can add the React-Image-Crop component. To do this, add the following code to your component:

5. Set the Aspect Ratio

By default, the React-Image-Crop component will allow users to crop the image in any shape or size. However, you can also set a specific aspect ratio for the crop. To do this, add the aspect attribute to the ReactCrop component:

6. Handle the Crop

Once the user has finished cropping the image, you’ll need to handle the crop. To do this, you can use the onChange attribute of the ReactCrop component. This attribute takes a function as an argument. This function will be called whenever the user changes the crop.

For example:

7. Compress the Image

Once you have the cropped image, you can compress it using a library like Sharp. To do this, you’ll need to install the Sharp library. To do this, open a terminal window and run the following command:

npm install sharp

Once the library is installed, you can use it to compress the image. For example:

const sharp = require(‘sharp’); const compressedImage = await sharp(croppedImage).jpeg({ quality: 80 }).toBuffer();

8. Upload the Image

Finally, you can upload the compressed image to your server. To do this, you can use a library like Axios. For example:

const axios = require(‘axios’); const response = await axios.post(‘/upload-image’, { image: compressedImage });
[ad_1]

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:

  1. Basic knowledge of ReactJS and JavaScript
  2. Node.js and npm installed on your computer
  3. 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:

  1. 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.
  2. getCroppedCanvas(options): This method allows you to specify additional options for the cropped canvas, such as the output type (jpeg or png), the output quality (0 to 1), and whether to include the original image’s metadata in the output.
  3. setCanvasData(data): This method sets the data for the canvas element. The data parameter should be an object that contains the following properties: left, top, width, height, naturalWidth, and naturalHeight.
  4. setCropBoxData(data): This method sets the data for the crop box. The data parameter should be an object that contains the following properties: left, top, width, and height.
  5. clear(): This method clears the canvas element.
  6. replace(url): This method replaces the current image with a new image specified by the url parameter. The canvas element is updated with the new image.
  7. disable(): This method disables the cropping functionality of the CropperJS instance.
  8. 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:

  1. Import the React and useState hooks from the react library, and import the Cropper class and its stylesheet from the cropperjs library.
  2. Define a functional component called ImageUpload that renders an input element of type “file” and a CropperJS instance.
  3. In the component’s state, define a image variable that will store the selected image, and a cropper variable that will store the instance of the CropperJS class.
  4. Define a function called handleFileInputChange that is called when the user selects an image file. This function reads the file using the FileReader API and sets the image state variable to the result.
  5. Define a function called handleCrop that is called when the user clicks the “Crop” button. This function gets a cropped canvas using the getCroppedCanvas method of the cropper instance, and then converts the canvas to a Blob using the toBlob method. The Blob is then logged to the console.
  6. 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 the cropper state variable to the instance of the CropperJS class.
  7. 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.

Recommended React JS Tutorials

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00