06 June, 2023

[ASP.NET] Using camera webcame in Website

Xin chào các bạn, bài viết hôm nay, mình chia sẻ các bạn source code mở camera trên website để chụp hình, code được viết bằng ASP.NET, các bạn có thể vào thư mục FrontEnd để copy full file css, js, html để sử dụng tùy theo ngôn ngữ các bạn.

[ASP.NET] Using camera webcame in Website



Để ứng dụng, có thể chạy mở được camera các bạn, nên chạy trên giao thức https.
Hoặc các bạn chép vào webserver: IIS hay Apache... để có thực bật chức năng sử dụng camera trên website nhé.
Code HTML:
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Demo Capture</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel='stylesheet' type='text/css' media='screen' href='style/webcam-demo.css'>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>  
    <script src="js/webcam-easy.min.js"></script> 
</head>
<body>
    <main id="webcam-app">
        <div class="form-control webcam-start" id="webcam-control">
                <label class="form-switch">
                <input type="checkbox" id="webcam-switch">
                <i></i> 
                <span id="webcam-caption">Click to Start Camera</span>
                </label>      
                <button id="cameraFlip" class="btn d-none"></button>                  
        </div>
        
        <div id="errorMsg" class="col-12 col-md-6 alert-danger d-none">
            Fail to start camera, please allow permision to access camera. <br/>
            If you are browsing through social media built in browsers, you would need to open the page in Sarafi (iPhone)/ Chrome (Android)
            <button id="closeError" class="btn btn-primary ml-3">OK</button>
        </div>
        <div class="md-modal md-effect-12">
            <div id="app-panel" class="app-panel md-content row p-0 m-0">     
                <div id="webcam-container" class="webcam-container col-12 d-none p-0 m-0">
                    <video id="webcam" autoplay playsinline width="640" height="480"></video>
                    <canvas id="canvas" class="d-none"></canvas>
                    <div class="flash"></div>
                    <audio id="snapSound" src="audio/snap.wav" preload = "auto"></audio>
                </div>
                <div id="cameraControls" class="cameraControls">
                    <a href="#" id="exit-app" title="Exit App" class="d-none"><i class="material-icons">exit_to_app</i></a>
                    <a href="#" id="take-photo" title="Take Photo"><i class="material-icons">camera_alt</i></a>
                    <a href="#" id="upload-photo" title="Upload Photo" class="d-none"><i class="material-icons">backup</i></a>
                    <a href="#" id="download-photo" download="selfie.png" target="_blank" title="Save Photo" class="d-none"><i class="material-icons">file_download</i></a>  
                    <a href="#" id="resume-camera"  title="Resume Camera" class="d-none"><i class="material-icons">camera_front</i></a>
                </div>
            </div>        
        </div>
        <div class="md-overlay"></div>
    </main>
    <script src='js/app.js'></script>
</body>
</html>

File app.js
const webcamElement = document.getElementById('webcam');

const canvasElement = document.getElementById('canvas');

const snapSoundElement = document.getElementById('snapSound');

const webcam = new Webcam(webcamElement, 'user', canvasElement, snapSoundElement);


$("#webcam-switch").change(function () {
    if(this.checked){
        $('.md-modal').addClass('md-show');
        webcam.start()
            .then(result =>{
               cameraStarted();
               console.log("webcam started");
            })
            .catch(err => {
                displayError();
            });
    }
    else {        
        cameraStopped();
        webcam.stop();
        console.log("webcam stopped");
    }        
});

$('#cameraFlip').click(function() {
    webcam.flip();
    webcam.start();  
});

$('#closeError').click(function() {
    $("#webcam-switch").prop('checked', false).change();
});

function displayError(err = ''){
    if(err!=''){
        $("#errorMsg").html(err);
    }
    $("#errorMsg").removeClass("d-none");
}

function cameraStarted(){
    $("#errorMsg").addClass("d-none");
    $('.flash').hide();
    $("#webcam-caption").html("on");
    $("#webcam-control").removeClass("webcam-off");
    $("#webcam-control").addClass("webcam-on");
    $(".webcam-container").removeClass("d-none");
    if( webcam.webcamList.length > 1){
        $("#cameraFlip").removeClass('d-none');
    }
    $("#wpfront-scroll-top-container").addClass("d-none");
    window.scrollTo(0, 0); 
    $('body').css('overflow-y','hidden');
}

function cameraStopped(){
    $("#errorMsg").addClass("d-none");
    $("#wpfront-scroll-top-container").removeClass("d-none");
    $("#webcam-control").removeClass("webcam-on");
    $("#webcam-control").addClass("webcam-off");
    $("#cameraFlip").addClass('d-none');
    $(".webcam-container").addClass("d-none");
    $("#webcam-caption").html("Click to Start Camera");
    $('.md-modal').removeClass('md-show');
}



$("#upload-photo").click(function () {
    let Image = document.querySelector('#download-photo').href.replace(/^data:image/[a-z]+;base64,/, "");
    const payload = {
        image : Image
    }

    $.ajax({
        type: 'POST',
        url: 'Default.aspx/SaveCapturedImage',
        processData: false,
        contentType: 'application/json',
        data: JSON.stringify(payload),
        success: function (response) {
            var jData = JSON.parse(response.d);
            
            Toastify({
                gravity: "top", 
                position: "right",
                duration: 3000,
                text: jData.message,
                className: "info",              
                style: {
                    background: jData.status ? "linear-gradient(to right, #00b09b, #96c93d)" : "linear-gradient(to right, #F70000, #7D1713)",
                }
            }).showToast();

            if (jData.status) {
                $("#resume-camera").click();
            }
          
        }
    });
});

$("#take-photo").click(function () {
    beforeTakePhoto();
    let picture = webcam.snap();
    document.querySelector('#download-photo').href = picture;
    afterTakePhoto();

   // console.log(picture);
});

function beforeTakePhoto(){
    $('.flash')
        .show() 
        .animate({opacity: 0.3}, 500) 
        .fadeOut(500)
        .css({'opacity': 0.7});
    window.scrollTo(0, 0); 
    $('#webcam-control').addClass('d-none');
    $('#cameraControls').addClass('d-none');
}

function afterTakePhoto(){
    webcam.stop();
    $('#canvas').removeClass('d-none');
    $('#take-photo').addClass('d-none');
    $('#exit-app').removeClass('d-none');
    $('#download-photo').removeClass('d-none');
    $('#upload-photo').removeClass('d-none');
    $('#resume-camera').removeClass('d-none');
    $('#cameraControls').removeClass('d-none');
}

function removeCapture(){
    $('#canvas').addClass('d-none');
    $('#webcam-control').removeClass('d-none');
    $('#cameraControls').removeClass('d-none');
    $('#take-photo').removeClass('d-none');
    $('#exit-app').addClass('d-none');
    $('#download-photo').addClass('d-none');
    $('#upload-photo').addClass('d-none');
    $('#resume-camera').addClass('d-none');
}

$("#resume-camera").click(function () {
    webcam.stream()
        .then(facingMode =>{
            removeCapture();
        });
});

$("#exit-app").click(function () {
    removeCapture();
    $("#webcam-switch").prop("checked", false).change();
});

Chi tiết các bạn có thể download full source code bên dưới về để sử dụng.
DOWNLOAD FULL CODE
DOWNLOAD NOW

Mật Khẩu Giải Nén : hungqb.com
All Right Reserved © 2015 By Hung Pro VN
Hung.Pro.VN Sharing Your Own Knowledge and Creative Thinking Every Day and Many Other Things.