Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Javascript Webcam Capture & Upload Local Image to Firebase Storage in Browser

Posted on November 19, 2022

 

 

Welcome folks today in this blog post we will be uploading the image taken by the webcam in browser to firebase storage using javascript. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

First of all guys in this application we will be doing the below tasks

 

 

  1. Uploading Image which is taken by webcam to firebase storage

2 Uploading Local Image File to Firebase Storage

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
<input type="file" id="photo" />
    <button onclick="uploadImage()">Upload Image</button>
    <!-- Stream video via webcam -->
 
    <video id="video" width=400 height=400 playsinline controls autoplay></video>
 
    <!-- Trigger canvas web API -->
    <button id="snap">Capture</button>
 
    <!-- Webcam video snapshot -->
    <canvas id="canvas" width="640" height="480"></canvas>

 

 

 

As you can see we have the input file widget where we will select any image file and then upload to firebase storage and we have the submit button. And we have attached the onclick event listener. So when we click the upload image button. Then we will be executing the uploadImage() method to actually upload the image file to firebase storage.

 

And also we have the video element where we will be showing the live webcam feed of the user when they allow the permission of camera inside the browser. And then inside this video element we have attached the width and height to 400 each. And also we have given the controls attribute to give the video player some of it’s controls. And it will be autoplaying whenever you load the page. And then we have the snap picture button so that when you click the button you will be able to upload the captured image to firebase storage. And lastly we have the canvas element where we will be showing the captured image inside the canvas. And we have given the height and the width of the canvas to be 640 and 480.

 

 

 

 

 

 

Getting the Credentials from Firebase

 

 

Now we need to get the required credentials from the firebase developer console. For that we need to create a new firebase project. And then inside it we need to go to project settings and inside it create a new web app and after creating it you will get the below code that you need to copy that and store it somewhere else we will need it.

 

 

 

 

 

 

 

 

As you can see we have got the shown above firebase config object this will be different for your project. So just store and copy it we will need this information to upload image to firebase storage.

 

 

Updating the Rules For Firebase Storage

 

 

Now guys you need to overwrite the rules for firebase storage. For this we need to allow the permission to read and write for everyone. You can do this as shown below

 

 

 

 

Writing the Javascript Code

 

 

Now guys we will be writing the javascript code for this application which is shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
var firebaseConfig = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "",
        appId: ""
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    console.log(firebase);

 

 

Now guys you need to copy paste your required firebase configuration object that you created in the earlier step to upload images to firebase storage. Your information will be different simply replace the values as shown above.

 

 

1
2
3
4
const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const snap = document.getElementById("snap");
    const errorMsgElement = document.querySelector('span#errorMsg');

 

 

As you can see we are getting the references of all the DOM elements using their id which we have given in the html.

 

 

JavaScript
1
2
3
4
5
6
const constraints = {
        audio: false,
        video: {
            width: 400, height: 400
        }
    };

 

 

And now we are setting the options object for our webcam capture. So here as you can see we are disabling audio we only need the video in the webcam. And we have provided fixed width and height of the webcam which is 400.

 

 

Showing Webcam on Loading the Page

 

 

Now guys we will showing the webcam when we load the page for this you need to copy paste the below code

 

 

JavaScript
1
2
// Load init
init();

 

 

For this we are calling the init() method when we load the page. For this we need to define this function as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
// Access webcam
    async function init() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia(constraints);
            handleSuccess(stream);
        } catch (e) {
            errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
        }
    }

 

 

As you can see inside this init method we are first of all getting the webcam of the user using the navigator class in the browser we are using the mediaDevices.getUserMedia() method to get access to the webcam and then we calling the handleSuccess() method and here we are passing the stream object. And if any error takes place we are catching it inside the catch() block.

 

 

JavaScript
1
2
3
4
5
// Success
    function handleSuccess(stream) {
        window.stream = stream;
        video.srcObject = stream;
    }

 

 

As you can see we are getting the stream object of the user. And here we are simply attaching it to the window.stream property. And then also showing the webcam feed of the user inside the video dom element by editing it’s srcObject property as shown above.

 

 

 

 

 

As you can see when you load the page you need to allow the permission inside the browser to allow the access of the webcam

 

 

 

As you can see the user webcam feed displaying inside the video And also we have the capture button to capture the photo from the webcam feed.

 

 

Uploading Local Image to Firebase Storage

 

 

Now guys we will writing the function when we click the upload image button after we select the local image from our computer as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function uploadImage() {
        const ref = firebase.storage().ref();
        const file = document.querySelector("#photo").files[0];
        const name = +new Date() + "-" + file.name;
        const metadata = {
            contentType: file.type
        };
        const task = ref.child(name).put(file, metadata);
        task
            .then(snapshot => snapshot.ref.getDownloadURL())
            .then(url => {
                console.log(url);
                document.querySelector("#image").src = url;
            })
            .catch(console.error);
    }

 

 

As you can see in the code above guys we are first of all getting the reference of the firebase storage object and then we are getting the file which the user has selected and then we are setting the name of the uploaded image. Here we are given the random name by using the date() constructor. And then we are making the metadata object. Inside it we have a single property which is the contentType of the image and then we are simply calling the child() method of firebase to create a new child element inside firebase storage and then we are passing the actual image and metadata as arguments to that function. And this function returns the promise and we are handling the promise using the then() statement and we are uploading the image to firebase storage. After the upload process is over we get the downloadURL of the uploaded image and then we are displaying the uploaded image in the DOM as shown below

 

 

 

 

 

 

 

As you can see the local image file selected by the user in browser is successfully uploaded to firebase storage in the firebase console.

 

 

Uploading Webcam Captured Image to Firebase Storage

 

 

Now we will be capturing the photo using webcam and then uploading to firebase storage as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Draw image
    var context = canvas.getContext('2d');
    snap.addEventListener("click", function () {
        context.drawImage(video, 0, 0, 640, 480);
        var image = new Image();
        image.id = "pic";
        image.src = canvas.toDataURL();
        console.log(image.src)
        var button = document.createElement('button')
        button.textContent = 'Upload Image'
        document.body.appendChild(button)
 
        button.onclick = function () {
            const ref = firebase.storage().ref();
            ref.child(new Date() + '-' + 'base64').putString(image.src, 'data_url').then(function (snapshot) {
                console.log('Uploaded a data_url string!');
                alert("Image Uploaded")
            });
        }
    });

 

 

As you can see in the above code we are drawing the webcam captured image inside the canvas using the 2d context. And for this we are using the drawImage() method to draw image on the canvas and after that we are converting the image to base64 code using the toDataURL() method. After getting the base64 code of the image we are simply uploading the image base64 code to the firebase storage and after it’s successfully we are simply alerting the user that the image file is successfully uploaded as shown below

 

 

 

 

 

 

Full Javascript Code

 

 

Wrapping the blog post guys this is the full javascript code

 

 

script.js

 

 

JavaScript
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
76
77
78
79
80
81
82
83
84
85
86
<script src="https://www.gstatic.com/firebasejs/7.7.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.7.0/firebase-storage.js"></script>
 
<script>
    var firebaseConfig = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "",
        appId: ""
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    console.log(firebase);
 
    function uploadImage() {
        const ref = firebase.storage().ref();
        const file = document.querySelector("#photo").files[0];
        const name = +new Date() + "-" + file.name;
        const metadata = {
            contentType: file.type
        };
        const task = ref.child(name).put(file, metadata);
        task
            .then(snapshot => snapshot.ref.getDownloadURL())
            .then(url => {
                console.log(url);
                document.querySelector("#image").src = url;
            })
            .catch(console.error);
    }
 
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const snap = document.getElementById("snap");
    const errorMsgElement = document.querySelector('span#errorMsg');
 
    const constraints = {
        audio: false,
        video: {
            width: 400, height: 400
        }
    };
 
    // Access webcam
    async function init() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia(constraints);
            handleSuccess(stream);
        } catch (e) {
            errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
        }
    }
 
    // Success
    function handleSuccess(stream) {
        window.stream = stream;
        video.srcObject = stream;
    }
 
    // Load init
    init();
 
    // Draw image
    var context = canvas.getContext('2d');
    snap.addEventListener("click", function () {
        context.drawImage(video, 0, 0, 640, 480);
        var image = new Image();
        image.id = "pic";
        image.src = canvas.toDataURL();
        console.log(image.src)
        var button = document.createElement('button')
        button.textContent = 'Upload Image'
        document.body.appendChild(button)
 
        button.onclick = function () {
            const ref = firebase.storage().ref();
            ref.child(new Date() + '-' + 'base64').putString(image.src, 'data_url').then(function (snapshot) {
                console.log('Uploaded a data_url string!');
                alert("Image Uploaded")
            });
        }
    });
</script>

Recent Posts

  • Build a JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • React-Admin Example to Create CRUD REST API Using JSON-Server Library in Browser Using Javascript
  • Javascript Papaparse Example to Parse CSV Files and Export to JSON File and Download it as Attachment
  • Javascript Select2.js Example to Display Single & Multi-Select Dropdown & Fetch Remote Data Using Ajax in Dropdown
  • Video.js Video Player Plugin Library in Javascript For Playing Videos in Browser
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme