aboutsummaryrefslogtreecommitdiff
path: root/frontend/src/components/ImageProcessor.tsx
blob: bdcae19cd756de744a8484664f8c47b8fa57cbea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import React, { useState } from 'react';

const BACK_END_URL = 'http://localhost:5000'

const ImageProcessor = (): JSX.Element => {
  const [file, setFile] = useState<File | null>(null);
  const [downloadUrl, setDownloadUrl] = useState<string>('');

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
    if (event.target.files) {
      setFile(event.target.files[0]);
    }
  };

  const processImage = async (operation: 'edge_detection' | 'color_inversion'): Promise<void> => {
    if (!file) {
      alert('Please select a file first!');
      return;
    }

    const formData = new FormData();
    formData.append('image', file);
    formData.append('operation', operation);

    try {
      const response = await fetch(`${BACK_END_URL}/upload`, {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();
      if (response.ok) {
        setDownloadUrl(`${data.processed_file}`);
        console.log(data.processed_file)
        alert('File processed successfully!');
      } else {
        alert(data.error || 'Failed to process the file');
      }
    } catch (error) {
      alert('Error connecting to the server');
    }
  };

  const downloadImage = (): void => {
    if (!downloadUrl) {
      alert('No processed image available for download!');
      return;
    }
    window.open(downloadUrl);
  };

  return (
    <div className="p-8 bg-white rounded-lg shadow-md flex flex-col items-center">
      <h2 className="text-2xl font-bold mb-4">Image Processing</h2>
      <div className="mb-4">
        <label className="block mb-2">Upload an image</label>
        <input type="file" onChange={handleFileChange} className="mb-4" />
      </div>
      <div className="flex flex-row justify-between w-full mb-4">
        <button onClick={() => processImage('edge_detection')} className="bg-black text-white font-bold py-2 px-4 rounded w-full mr-2">
          Edge Detection
        </button>
        <button onClick={() => processImage('color_inversion')} className="bg-black text-white font-bold py-2 px-4 rounded w-full ml-2">
          Color Inversion
        </button>
      </div>
      <img className='border-8 border-red-50' src={downloadUrl == '' ? "https://placehold.co/600x400" : downloadUrl} />
      <button onClick={downloadImage} className="bg-black text-white font-bold py-2 px-4 rounded w-full">
        Download
      </button>
    </div>
  );
};

export default ImageProcessor;