Capture image with webcam and send it to API as base64 or as image (buffer?)

So, the idea is to capture an image using the laptop webcam on React, and after getting the image, send it to an API either as a base64 string or as an image (maybe this last one would be a buffer?)

How can I do that? I found nothing clear on internet 😦 maybe I am not understanding well
UUUnknown User10/18/2022
2 Messages Not Public
Sign In & Join Server To View
@casarin - Hey I took some time this afternoon to get this set up:
import { useEffect, useRef, useState } from "react";

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

    useEffect(() => {
        if (navigator.mediaDevices.getUserMedia) {
                .getUserMedia({ video: true })
                .then(function (stream) {
                    videoRef.current.srcObject = stream;
                .catch(function (error) {
                    console.log("Something went wrong!", error);
    }, []);

    const takePicture = function () {
        const context = canvasRef.current.getContext("2d");
        context.drawImage(videoRef.current, 0, 0, 640, 480);

    const uploadPicture = async function () {
        const image = canvasRef.current.toDataURL("image/png");
        const response = await fetch("/api/upload", {
            method: "POST",
            body: image,
        const data = await response.json();

    return (
        <div className="container">
            <video ref={videoRef} width="640" height="480" />

            <div className="controls">
                <canvas ref={canvasRef} width="640" height="480"></canvas>
                    <button onClick={takePicture}>Take Picture</button>
                    <br />
                    <button onClick={uploadPicture}>Upload Picture</button>
                    <br />
            {imageUrl && (
                <a href={imageUrl} target="_blank" rel="noopener noreferrer">
const cloudinary = require("cloudinary").v2;

cloudinary.config({ secure: true });

export default async function handler(req, res) {
    try {
        const result = await cloudinary.uploader.upload(req.body, {
            folder: "webcamtest",
    } catch (error) {
This is using the Cloudinary API and Node.js SDK for the uploads, but you could swap out whatever API you wanted.
yo, thanks for that link, it wasnt available when i searched for the subject... just for curiosity, what did you mean with "Hope ethos is being considered"? ahhaha
hey @joeydi what a cool implementation, lol!
I think this would fit as the solution for the topic 😄
thanks a lot!
UUUnknown User10/19/2022
Message Not Public
Sign In & Join Server To View