Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.8 kB
1
Indexable
Never
// Dashboard.js

import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Link } from 'react-router-dom';
import imageCompression from 'browser-image-compression';

const Dashboard = () => {
  const navi = useNavigate();

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

    try {
      const compressedImages = await Promise.all(
        newImages.map(async (image) => {
          if (image.size > 2 * 1024 * 1024) {
            // Compress image if size exceeds 2 MB
            const compressedImage = await imageCompression(image, {
              maxSizeMB: 2,
              useWebWorker: true,
            });
            return compressedImage;
          } else {
            return image;
          }
        })
      );

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

      // Store base64 strings in local storage
      localStorage.setItem('uploadedImages', JSON.stringify(base64Images));
    } catch (err) {
      console.log(err);
      // Handle error, maybe show a notification to the user
    }
  };

  return (
    <>
      <header>
        <nav>
          <div className="nav-left">
            <h1>Sample App</h1>
          </div>
          <div className="nav-right">
            <p>Welcome !!!!! {localStorage.getItem('name')}</p>
            <Link to="/Dashboard">Dashboard</Link>
            <br />
            <input type="file" onChange={handleImageChange} multiple />
            <br />
            <br />
            <Link to="/FetchImage">Images</Link>
          </div>
        </nav>
      </header>

      <br />
      <br />

      <button onClick={() => navi('/Weatherdata')}>Weather Search</button>
    </>
  );
};

export default Dashboard;

// ImageFetcher.js

import React, { useEffect, useState } from 'react';

const ImageFetcher = () => {
  const [fetchedImages, setFetchedImages] = useState([]);

  useEffect(() => {
    // Fetch stored images from local storage
    const storedImages = localStorage.getItem('uploadedImages');

    // Parse stored base64 strings and convert them back to images
    if (storedImages) {
      const base64Images = JSON.parse(storedImages);
      setFetchedImages(base64Images);
    }
  }, []);

  return (
    <div className="image-grid-container">
      <h2>Fetched Images</h2>
      <div className="image-grid">
        {fetchedImages.map((base64String, index) => (
          <div key={index} className="image-item">
            <img src={base64String} alt={`Uploaded ${index}`} />
          </div>
        ))}
      </div>
    </div>
  );
};

export default ImageFetcher;
Leave a Comment