React js Resize, Crop, Compress Image Before Upload Tutorial

React js Resize, Crop, Compress Image Before Upload Tutorial

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

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to React js Resize, Crop, Compress Image Before Upload Tutorial

  1. How to compress it ?

Leave a Reply

Your email address will not be published. Required fields are marked *