Home

Boost React App Performance with Image Compression Techniques

20 views

Compressing images before uploading them in a React application can help reduce file size, improve loading times, and enhance the user experience. To perform image compression, you can use libraries like browser-image-compression or react-image-file-resizer. Here's a step-by-step guide using the browser-image-compression library:

Step-by-step Guide

  1. Install the Library

    First, you need to install the browser-image-compression library in your React project. You can do this using npm or yarn:

    npm install browser-image-compression
    

    or

    yarn add browser-image-compression
    
  2. Create an Image Upload and Compression Component

    Below is an example of a React component that compresses an image before uploading:

    import React, { useState } from "react";
    import imageCompression from "browser-image-compression";
    
    const ImageUploader = () => {
      const [compressedImage, setCompressedImage] = useState(null);
      const [originalFile, setOriginalFile] = useState(null);
    
      const handleFileChange = async (event) => {
        const file = event.target.files[0];
        setOriginalFile(file);
        if (!file) return;
    
        try {
          const options = {
            maxSizeMB: 1,          // (Optional) Max size in MB
            maxWidthOrHeight: 800, // (Optional) Max width or height
            useWebWorker: true,    // (Optional) Use multi-threading for faster compression
          };
    
          const compressedFile = await imageCompression(file, options);
          setCompressedImage(compressedFile);
    
          // For demonstration, logging the compressed file size
          console.log(
            `Original Size: ${file.size / 1024} KB, Compressed Size: ${compressedFile.size / 1024} KB`
          );
    
          // If you want to upload the compressed file:
          // const formData = new FormData();
          // formData.append("image", compressedFile);
          // upload to your server
        } catch (error) {
          console.error("Error while compressing image:", error);
        }
      };
    
      return (
        <div>
          <input type="file" onChange={handleFileChange} accept="image/*" />
          {originalFile && (
            <p>Original Size: {(originalFile.size / 1024).toFixed(2)} KB</p>
          )}
          {compressedImage && (
            <p>
              Compressed Size: {(compressedImage.size / 1024).toFixed(2)} KB
            </p>
          )}
        </div>
      );
    };
    
    export default ImageUploader;
    

Explanation

  • handleFileChange: This function is triggered when a user selects an image file. It manages image compression using the imageCompression function provided by browser-image-compression.

  • Options: You can set options like maxSizeMB to define the maximum size you want for the compressed image, maxWidthOrHeight for dimension constraints, and useWebWorker to speed up the compression process.

  • File Input: Users can select an image file to upload. The component then compresses the image and shows the original and compressed file sizes.

Using this method, you ensure that images are user-friendly in terms of loading time and bandwidth usage without compromising too much on quality. Always test with various images to find the best compression settings for your use case.