Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.4 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);

    // Check if each file exceeds 2MB
    const exceedsLimit = newImages.some(file => file.size > 2 * 1024 * 1024); // 2MB in bytes

    if (exceedsLimit) {
      // Compress and store files exceeding 2MB in local storage
      const compressedImages = await Promise.all(newImages.map(compressImage));
      const base64Images = compressedImages.map(image => URL.createObjectURL(image));
      localStorage.setItem('uploadedImages', JSON.stringify(base64Images));
    } else {
      // Convert images to base64 strings
      const base64Images = newImages.map(image => URL.createObjectURL(image));
      // Store base64 strings in local storage
      localStorage.setItem('uploadedImages', JSON.stringify(base64Images));
    }
  };

  const compressImage = async (file) => {
    // Compress the image if it exceeds 2MB
    const compressedImage = await new ImageCompressor(file, {
      quality: 0.6,
      maxWidth: 800,
      maxHeight: 800,
    }).then(({ blob }) => blob);

    return compressedImage;
  };

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

export default ImageUploader;
Leave a Comment