Spaces:
Build error
Build error
| 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> | |
| ); | |
| } | |