How to Fully Control Webcam Stream Params in HTML Page

If you want to open webcam stream in a web browser, what technology will you choose? Probably many developers’ answer is HTML5. Yes, with the JavaScript API getUserMedia, it will be pretty easy to open webcam within web browsers. However, the API is not supported by some old web browsers like Internet Explorer 6, 7 and 8. Besides that, the HTML5 interface cannot fully configure camera parameters such as exposure, focus and etc. Therefore, if you want to build a professional camera solution for a web project, HTML5 is not the best choice. This is why Dynamsoft made the solution. Dynamsoft Camera SDK is a JavaScript webcam SDK for Windows with DirectShow under the hood. It allows developers to quickly build online webcam viewer with a few lines of HTML and JavaScript code and fully control and adjust camera settings within web browsers.
Read more

How to Make Web Barcode Reader with NodeJS REST Framework

As cloud computing market continues to skyrocket, more and more IT companies tend to release cloud APIs for developers. Most cloud APIs are exposed via REST (Representational state transfer) Web service. In this post, I will illustrate how to create a barcode reader with Node REST Framework Restify and Dynamsoft Barcode Reader SDK.

Read more

Making AngularJS Work with DWT

AngularJS is a Web application framework for rendering dynamic Web content with MVC architecture. It reduces amount of JavaScript code with the feature of two-way data binding. More and more developers tend to use Angular for client-side development. Therefore, I’d like to share how to change the basic scanning demo of Dynamic Web TWAIN SDK with AngularJS today.

Read more

How to Use Edge.js to Empower WebSocket Solutions in JavaScript

A few days ago, I read the article – Run .NET and Node.js code in-process with Edge.js, which inspired me to try a new way of WebSocket solutions in JavaScript. It is known that Node.js makes applications, which written in JavaScript, run on server-side. Let’s see how we can quickly implement image transmission between servers and clients in a few lines of code.

Read more

Draw the Board | Modern Ludo

Today we start making our Modern Ludo Game from scratch.

The first thing to do is draw the board. For this part, we’ll simply use the <Canvas> in HTML5.

The MarkUp is very simple:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>ModernLudo</title>
    <link rel="stylesheet" type="text/css" href="Styles/modernludo.css" />
</head>
<body>
    <div id="playGround" style="display:none;">
        <div id="main">
            <canvas id="gameboard"></canvas>
        </div>
    </div>
    <script type="text/javascript" src="Scripts/modernludo.js"></script>
</body>
</html>

CSS:

body {
    padding: 0;
    margin: 0 auto;
    overflow-y: hidden;
    background-color: #0D0D0D;
}
div#main {
    background-color: khaki;
    margin: 0 auto;
    padding: 0;
}

#gameboard {
    position: absolute;
    margin: 0;
    padding: 0;
    box-sizing: padding-box;
}

The important part is the JavaScript. How to actually draw the board:

  1. Placing the board in the browser window. Considering that we want to build an application that runs in web browsers, we need to make sure that our board can adjust itself to fit a browser window of any size:
    function refreshBoard() {
        canvasWidth = window.innerHeight - 10;
        canvasHeight = window.innerHeight;
        maindiv.style.width = canvasWidth + "px";
        maindiv.style.height = canvasWidth + "px";
        ctx.canvas.width = canvasWidth;
        ctx.canvas.height = canvasWidth;
    }
  2. Creating the background. Our game is Modern Ludo, so a blue sky makes for a good background:  Read more

A Simple Chrome Extension to Save Web Page Screenshots to Local Disk

A Chrome extension is a package of files including a manifest file, HTML files, JavaScript files and other resources. With extensions, we can add more functionalities to empower Chrome.

Getting Started with Chrome Extension

Anatomy of Web Page Screenshots

The manifest file:

{

    "name": "Screenshot Extension",

    "version": "1.0",

    "description": "A simple screenshot extension",

    "background": {

        "persistent": false,

        "scripts": ["background.js"]

    },

    "content_scripts": [

        {

            "matches" : ["<all_urls>"],

            "js": ["content.js"]

        }

    ],

    "browser_action": {

        "default_icon": "camera.png",

        "default_title": "Screenshot"

    },

    "permissions": ["tabs", "<all_urls>", "activeTab"],

    "manifest_version": 2

}
  • The background.js controls the logic of the extension, whereas content.js interacts with web pages. They send messages to communicate with each other.
  • If you want to make your extension work for all web sites, you have to set the permission <all_urls>

Capture the visible area of the web page when clicking the extension icon:

       chrome.browserAction.onClicked.addListener(function(tab) {

            chrome.tabs.captureVisibleTab(null, {

                format : "png",

                quality : 100

            }, function(data) {

                screenshot.data = data;

            });

        });

Message passing between the extension and web pages:

  • In background.js
                  chrome.tabs.query({

                        active : true,

                        currentWindow : true

                    }, function(tabs) {

                        chrome.tabs.sendMessage(tabs[0].id, {ready : "ready"}, function(response) {

                            if (response.download === "download") {

                            }

                        });

                    });
  • In content.js
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {

    if (msg.ready === "ready") {

        if (confirm('Do you want to capture the screen?')) {

            sendResponse({download : "download"});

        }

    }

});

Save the screenshot:

    saveScreenshot : function() {

        var image = new Image();

        image.onload = function() {

            var canvas = screenshot.content;

            canvas.width = image.width;

            canvas.height = image.height;

            var context = canvas.getContext("2d");

            context.drawImage(image, 0, 0);

            // save the image

            var link = document.createElement('a');

            link.download = "download.png";

            link.href = screenshot.content.toDataURL();

            link.click();

            screenshot.data = '';

        };

        image.src = screenshot.data;

    },

Install and Run Chrome Extension

  • Check Developer mode.
  • Click Load unpacked extension to select your project folder.load chrome extension
  • Open a web page and click the extension icon in the toolbar.
  • Confirm and save the screenshot.

Download Sample Code

Chrome_Screenshot

Image Transmission between a HTML5 WebSocket Server and a Web Client

HTML5 WebSocket facilitates the communication between web browsers and local/remote servers. If you want to learn a simple websocket example, creating a WebSocket Server in C# and a Web client in JavaScript, you can refer to SuperWebSocket, which is a .NET implementation of Web Socket Server.

In this article, I would like to share how I implemented a simple WebSocket solution for image transmission based on the basic sample code of SuperWebSocket and Dynamic .NET TWAIN, especially what problem I have solved.

Here is a quick look of the WebSocket server and the HTML5 & JavaScript client.

WebSocket ServerWebSocket Client

Prerequisites

Create a .NET WebSocket Server

Create a new WinForms project, and add the following references which are located at the folder of SuperWebSocket.

WebSocket References

Add the required namespaces:

using Dynamsoft.DotNet.TWAIN;

using SuperSocket.SocketBase;
using SuperWebSocket;

In the sample code, the server is launched with port 2012, no IP specified by default. You can specify the IP address for remote access. For example:

if (!appServer.Setup("192.168.8.84", 2012)) //Setup with listening port
{
     MessageBox.Show("Failed to setup!");
     return;
}

You can use Dynamic Web TWAIN component to do some image operation. With two lines of code, I can load an image file:

bool isLoad = dynamicDotNetTwain.LoadImage("dynamsoft_logo_black.png"); // load an image
Image img = dynamicDotNetTwain.GetImage(0);

Be careful of the image format. It is PNG. If you want to display it in a Web browser, you need to convert the format from PNG to BMP:

            byte[] result;
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);   // convert png to bmp
                result = stream.GetBuffer();
            }

It’s not done yet. The byte array contains some extra image information, which is 54 bytes in length. So the actual data length is:

int iRealLen = result.Length - 54;
byte[] image = new byte[iRealLen];

Here are some tricky things that if you just send the subset of the byte array to your Web browser, you will find the displayed image is upside-down, and the color is also incorrect.

To fix the position issue, you need to sort the bytes of original data array from bottom to top. As to the color, exchange the position of blue and red. See the code:

            int iIndex = 0;
            int iRowIndex = 0;
            int iWidth = width * 4;
            for (int i = height - 1; i >= 0; --i)
            {
                iRowIndex = i * iWidth;
                for (int j = 0; j < iWidth; j += 4)
                {
                    // RGB to BGR
                    image[iIndex++] = result[iRowIndex + j + 2 + 54]; // B
                    image[iIndex++] = result[iRowIndex + j + 1 + 54]; // G
                    image[iIndex++] = result[iRowIndex + j + 54];     // R
                    image[iIndex++] = result[iRowIndex + j + 3 + 54]; // A
                }   
            }

Now, you can send the data via:

session.Send(imageData.Data, 0, imageData.Data.Length);

Create a JavaScript Client

To receive the image as ArrayBuffer on the client side, you have to specify the binaryType after creating a WebSocket:

ws.binaryType = "arraybuffer";

Once the image data is received, draw all bytes onto a new canvas, and finally create an image element to display the canvas data:

                var imageWidth = 73, imageHeight = 73; // hardcoded width & height. 
                var byteArray = new Uint8Array(data);

                var canvas = document.createElement('canvas');
                canvas.height = imageWidth;
                canvas.width = imageHeight;
                var ctx = canvas.getContext('2d');

                var imageData = ctx.getImageData(0, 0, imageWidth, imageHeight); // total size: imageWidth * imageHeight * 4; color format BGRA
                var dataLen = imageData.data.length;
                for (var i = 0; i < dataLen; i++)
                {
                    imageData.data[i] = byteArray[i];
                }
                ctx.putImageData(imageData, 0, 0);

                // create a new element and add it to div
                var image = document.createElement('img');
                image.width = imageWidth;
                image.height = imageHeight;
                image.src = canvas.toDataURL();

                var div = document.getElementById('img');
                div.appendChild(image);

Download Sample

WebSocketImageSendSource

How to Upload HTML Canvas Data to PHP Server

Last time, I shared my experience about how to use JavaScript saving HTML canvas data to local disk in Chrome. In this tutorial, I would like to share how to save HTML canvas data to remote service with JavaScript and PHP.

Dynamsoft Barcode Reader SDK
Ads Powered by Dynamsoft

Uploading canvas data is a little bit complicated comparing to file upload. If you want to learn how to upload a file, you can read the tutorial PHP File Upload.

Let’s get started to create a project, which includes two files upload.html and upload_data.php. In addition, you need to create a folder upload for receiving files.

upload.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Upload Canvas Data to PHP Server</title>
	</head>
	<body>
		<h1>Upload Canvas Data to PHP Server</h1>
		<canvas width="80" height="80" id="canvas">canvas</canvas>
		<script type="text/javascript">
			window.onload = function() {
				var canvas = document.getElementById("canvas");
				var context = canvas.getContext("2d");
				context.rect(0, 0, 80, 80);
				context.fillStyle = 'yellow';
				context.fill();
			}
		</script>

		<div>
			<input type="button" onclick="uploadEx()" value="Upload" />
		</div>

		<form method="post" accept-charset="utf-8" name="form1">
			<input name="hidden_data" id='hidden_data' type="hidden"/>
		</form>

		<script>
			function uploadEx() {
				var canvas = document.getElementById("canvas");
				var dataURL = canvas.toDataURL("image/png");
				document.getElementById('hidden_data').value = dataURL;
				var fd = new FormData(document.forms["form1"]);

				var xhr = new XMLHttpRequest();
				xhr.open('POST', 'upload_data.php', true);

				xhr.upload.onprogress = function(e) {
					if (e.lengthComputable) {
						var percentComplete = (e.loaded / e.total) * 100;
						console.log(percentComplete + '% uploaded');
						alert('Succesfully uploaded');
					}
				};

				xhr.onload = function() {

				};
				xhr.send(fd);
			};
		</script>
	</body>
</html>
  • Create a canvas tag, and draw a rectangle on canvas when the whole page has been loaded.
  • Create a button for triggering uploading event.
  • Create a form with a hidden input tag, which is used to save the data URL.
  • Use XMLHttpRequest to asynchronously upload form data to PHP service.

upload_data.php:

<?php
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>

Now deploy the whole project to a web server, such as nginx, Apache and so forth. Visit localhost:port/upload.html, click the button, and open the file folder to check whether the image is there.

Anything unclear? Please feel free to contact me at {desmond at Dynamsoft dot com}.