File size: 1,965 Bytes
ff373c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Download } from "lucide-react";

export default function WebcamImageSaver() {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const [imageUrl, setImageUrl] = useState("");

  const startCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
      }
    } catch (error) {
      console.error("Error accessing webcam:", error);
    }
  };

  const captureImage = () => {
    if (!videoRef.current || !canvasRef.current) return;
    const context = canvasRef.current.getContext("2d");
    context.drawImage(videoRef.current, 0, 0, 640, 480);
    const imageDataUrl = canvasRef.current.toDataURL("image/png");
    setImageUrl(imageDataUrl);
  };

  const saveImage = () => {
    if (!imageUrl) return;
    const link = document.createElement("a");
    link.href = imageUrl;
    link.download = "webcam_image.png";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="flex flex-col items-center gap-4 p-4">
      <Button onClick={startCamera}>Start Camera</Button>
      <video ref={videoRef} autoPlay className="rounded-lg shadow-md" width={640} height={480} />
      <canvas ref={canvasRef} width={640} height={480} className="hidden" />
      <Button onClick={captureImage}>Capture Image</Button>
      {imageUrl && (
        <Card className="p-4">
          <CardContent>
            <img src={imageUrl} alt="Captured" className="rounded-lg shadow-md" />
            <Button onClick={saveImage} className="mt-4 flex items-center">
              <Download className="mr-2" /> Save Image
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  );
}