Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.3 kB
1
Indexable
Never
import React from 'react';
import ImageCompressor from 'image-compressor.js';

const ImageUploader = () => {
  const handleImageChange = async (e) => {
    const files = e.target.files;
    const newImages = Array.from(files);

    const compressedImages = await Promise.all(newImages.map(compressImage));

    // Convert compressed images to base64 strings
    const base64Images = compressedImages.map(image => URL.createObjectURL(image));

    // Store base64 strings in local storage
    localStorage.setItem('uploadedImages', JSON.stringify(base64Images));
  };

  const compressImage = async (file) => {
    if (file.size > 2 * 1024 * 1024) { // 2MB in bytes
      // Compress the image if it exceeds 2MB
      const compressedImage = await new ImageCompressor(file, {
        quality: 0.6,
        maxWidth: 800, // Adjust the maxWidth as needed
        maxHeight: 800, // Adjust the maxHeight as needed
        success(result) {
          // `result` is the compressed image
        },
        error(error) {
          console.error(error.message);
        },
      });
      return compressedImage;
    } else {
      return file;
    }
  };

  return (
    <div>
      <input type="file" onChange={handleImageChange} multiple />
    </div>
  );
};

export default ImageUploader;
Leave a Comment