How to Build a PHP Webcam App Using Dynamic Web TWAIN Add-on

Last Updated on

Want to enable users to capture pictures from within your PHP application? You can easily achieve it with the webcam add-on.

In this article, we will show you how to build a PHP webcam app to show live video stream, do online webcam capture and upload the images to a web server by using the webcam add-on of Dynamic Web TWAIN.

Installation

Download the latest version of Dynamic Web TWAIN.

System Requirements

  • Client-side: Windows; IE v6 or above, Chrome, Firefox; A UVC compatible webcam
  • Server-side: PHP 7.3

Basic Steps of Building a PHP Webcam App for Web Browsers

Resources

Copy Resources folder from Dynamic Web TWAIN Directory to your project.

Check whether the file Resources\addon\dynamsoft.webtwain.addon.webcam.js exists. If you forget to install the webcam addon, you have to re-install Dynamic Web TWAIN.

Currently, the addon is not available for download online.

PHP Code

Create an action page upload.php to receive the images from the web client-side:

<?php
	$strJson = "{\"success\":false}";
	
	try{

		$file = $_FILES["RemoteFile"];
		
		$fileName = $_POST["fileName"];
        if ($fileName == "" || $fileName == null) $fileName = $file["name"];
        
        $filePath = dirname(__FILE__) . "/upload/";
        if (!file_exists($filePath)) {
            mkdir($filePath);
        }

        if (file_exists($filePath . $fileName))
        {
            $iniNum = 0;
            if (strpos($fileName, "(") !== FALSE && strpos($fileName, ")") !== FALSE)
            {
                $leftPhPos =  strrpos($fileName, "(");
                $rightPhPos = strrpos($fileName, ")");
                if ($leftPhPos < $rightPhPos) {
                    $numStr = substr($fileName, $leftPhPos + 1, $rightPhPos - $leftPhPos - 1);
                    if (is_numeric($numStr))
                    {
                    	$iniNum = intval($numStr);
                        $fileName = substr($fileName, 0, $leftPhPos) . substr($fileName, $rightPhPos + 1);
                    }
                    else { 
                        $iniNum = 0;
                    }
                }
            }
            $indexPoint = strrpos($fileName, ".");
            $str1 = substr($fileName, 0, $indexPoint) . "(";
            $str2 = ")" . substr($fileName, $indexPoint);
            for ($i = $iniNum; ; ++$i)
            {
                if (!file_exists($filePath . ($str1 . $i . $str2)))
                {
                    $fileName = $str1 . $i . $str2;
                    break;
                }
            }
        }

		$fileFullPath = $filePath . $fileName;

		if(strpos($file["type"], 'text/plain') === false){
			move_uploaded_file($file["tmp_name"] , $fileFullPath);
		}else{
		    $file_contents = base64_decode(str_replace(' ', '+', file_get_contents($file['tmp_name'])));
		    file_put_contents($fileFullPath, $file_contents);
		}

		$strJson = "{\"success\":true, \"fileName\":\"" . $fileName . "\"}";
		

	}
	catch(Exception $ex){
		$strJson = "{\"success\":false, \"error\": \"" . ex.Message.Replace("\\", "\\\\") . "\"}";
	}	

    // Response.Clear();
    header("Content-Type: application/json; charset=utf-8");
    echo $strJson;
?>

HTML Code

Create an HTML web page index.html.

Create an HTML element as the web twain container:

<div id="dwtcontrolContainer"></div>

Initialize Dynamic Web TWAIN object and get the webcam list:

                Dynamsoft.WebTwainEnv.AutoLoad = false;
		Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used

		var DWObject;
		var isVideoOn = true;

		function Dynamsoft_OnReady() {
			DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer'
			if (DWObject) {
				DWObject.Width = 504;
				DWObject.Height = 600;

				var arySource = DWObject.Addon.Webcam.GetSourceList();
				for (var i = 0; i < arySource.length; i++)
					document.getElementById("source").options.add(new Option(arySource[i], arySource[i]), i); // Get Webcam Source names and put them in a drop-down box

			}

			document.getElementById('source').onchange = function () {
				DWObject.Addon.Webcam.SelectSource(document.getElementById("source").options[document.getElementById("source").selectedIndex].value);

				SetIfWebcamPlayVideo(true);
				disableButton(document.getElementById("btn-upload"));
			}

			document.getElementById('source').onchange();
		}

To play and stop the video, invoke the APIs as follows:

DWObject.Addon.Webcam.StopVideo();
DWObject.Addon.Webcam.PlayVideo(DWObject, 80, function () { });

Once an image is ready, you can upload it to the web server by calling HTTPUploadThroughPost():

        function upload() {
            if (DWObject) {
                // If no image in buffer, return the function
                if (DWObject.HowManyImagesInBuffer == 0)
                    return;

                var strHTTPServer = location.hostname; //The name of the HTTP server. For example: "www.dynamsoft.com";
                var CurrentPathName = unescape(location.pathname);
                var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
                var strActionPage = CurrentPath + "upload.php"; // Action page
                DWObject.IfSSL = false; // Set whether SSL is used
                DWObject.HTTPPort = location.port == "" ? 80 : location.port;

                var Digital = new Date();
                var uploadfilename = Digital.getMilliseconds(); // Uses milliseconds according to local time as the file name

                //Upload image in JPEG
                DWObject.HTTPUploadThroughPost(strHTTPServer, DWObject.CurrentImageIndexInBuffer, strActionPage, uploadfilename + ".jpg", OnHttpUploadSuccess, OnHttpUploadFailure);
            }
        } 

Web Server

To quickly deploy the PHP webcam project, you can use the PHP built-in web server:

php -S localhost:8000 

Since the webcam add-on is not WebRTC related, there is no compatibility issue. You can have fun with the app in any web browser (Note: Windows only).

php webcam app

If you have any questions about integrating webcam capture into a PHP application, please let us know.

Source Code

https://github.com/dynamsoft-dwt/webcam-addon

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe Newsletter

Subscribe to our mailing list to get the monthly update.

Subscribename@email.com