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}.

How to Implement a Real-time Commnication Application with WebRTC

Recently, I read the article – Getting Started with WebRTC, and also learned the sample code from WebRTC codelab. It is really interesting that we can implement video chat, audio chat and even message communications with WebRTC (Web browsers with real-time communications). In this post, I would like to share what I have done after digesting what WebRTC is.

What You Should Know?

  1. The sample code is based on the samples from codelab.
  2. You need to install Node.js.
  3. You need to use the npm, the package manager for Node.js, to install socket.io and node-static.

How to Run?

  1. Run command line tool (cmd.exe on Windows, terminal on Mac OS X) and get into the project root directory.
  2. Type in “node server.js”.
  3. Connect your devices (PC, smartphone, and tablet) to local network, and make sure you have installed the latest version of Chrome.
  4. Visit your local IP_address:2013 via arbitrary two devices.
  5. Enjoy it.

What is inside?

  • Video chat
  • Audio chat
  • Message communications
  • Capture camera image
  • Save image to local disk

Code

Video chat, audio chat and message communications:

var constraints = {video: true, audio : true};
getUserMedia(constraints, handleUserMedia, handleUserMediaError); // enable video & audio
function createPeerConnection() {
  try {
    pc = new RTCPeerConnection(null, {'optional': [{'DtlsSrtpKeyAgreement': true}, {'RtpDataChannels': true}]});
    pc.onicecandidate = handleIceCandidate;
    pc.onaddstream = handleRemoteStreamAdded; // receive remote video stream
    pc.onremovestream = handleRemoteStreamRemoved;
    console.log('Created RTCPeerConnnection');
  } catch (e) {
    console.log('Failed to create PeerConnection, exception: ' + e.message);
    alert('Cannot create RTCPeerConnection object.');
      return;
  }

  try {
      // Reliable Data Channels not yet supported in Chrome
      sendChannel = pc.createDataChannel("sendDataChannel",
        {reliable: false});
      sendChannel.onmessage = handleMessage;
      trace('Created send data channel');
    } catch (e) {
      alert('Failed to create data channel. ' +
            'You need Chrome M25 or later with RtpDataChannel enabled');
      trace('createDataChannel() failed with exception: ' + e.message);
    }
    sendChannel.onopen = handleSendChannelStateChange;
    sendChannel.onclose = handleSendChannelStateChange;
    pc.ondatachannel = gotReceiveChannel; // receive message
}

Capture camera image:

function captureImage() {
	if (remoteVideo.src == "") {
		alert('No remote connection');
		return;
	}

	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');

	canvas.width = remoteVideo.videoWidth / 4;
	canvas.height = remoteVideo.videoHeight / 4;
	ctx.drawImage(remoteVideo, 0, 0, canvas.width, canvas.height);
}

Save image to local disk:

function saveImage() {
	if (remoteVideo.src == "") {
		alert('No remote connection');
		return;
	}

	var ua = window.navigator.userAgent;

	if (ua.indexOf("Chrome") > 0) {
		var canvas = document.getElementById("canvas");

		// save image as png
		var link = document.createElement('a');
		link.download = "test.png";
		link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
		;
		link.click();
	} else {
		alert("Please use Chrome");
	}
}

You can download the source code WebRTC. If you have any questions, please email {desmond at Dynamsoft dot com}.

Take a Photo and Upload it on Mobile Phones with HTML5

In my daily life, I enjoy taking photos with my smartphone and uploading them to various websites. So I started thinking, “Is it possible to implement these functions in a web browser?” Although Dynamsoft ImageCapture Suite allows us to capture images from a webcam, it is designed for a desktop App development on windows and Mac, not for mobile platforms. Fortunately, the new HTML5 SDK is capable of uploading local images or captured images to web servers. Everything becomes easier if we have a mobile web browser, like Chrome, which is fully compatible with HTML5.

Read more

How to Use JavaScript to Save Canvas Data in Chrome

In HTML5, there is a new tag <canvas>, which is used to draw graphics via JavaScript. In this tutorial, I would like to share how to draw images on canvas, and how to save the canvas data to local disk by clicking button.

Dynamsoft Barcode Reader SDK
Ads Powered by Dynamsoft

Draw Images on Canvas

To develop web application, I prefer using Aptana Studio which contains a built-in web server.

Now, let’s create a basic web project which includes only a default index.html file.

aptana studio

Open index.html and add a <img> tag in <body>.

<img src="dynamsoft_logo_black.png" id="img" width="73" height="73" alt="dynamsoft"/>

Below the image, add a <canvas>.

<canvas width="73" height="73" id="canvas">canvas</canvas>

Create a button to trigger click event.

<button type="button" onclick="saveImage()">save image</button>

Draw the canvas when the page is finished loading.

<script type="text/javascript">
			window.onload = function() {
				var canvas = document.getElementById("canvas");
				var ctx = canvas.getContext("2d");
				var img = document.getElementById("img");
				ctx.drawImage(img, 0, 0);
			}
</script>

Run the project to see what we have done so far.

 GUI

Save Canvas Data to Local Disk

Finally, we can use following code to popup a dialog for saving the canvas data.

var canvas = document.getElementById("canvas");
document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

Both Chrome and Firefox support the method, whereas they behave differently.

Chrome

Chrome

Firefox 

Firefox

The problem is that we cannot programmatically set the file name and type.

Fortunately, there is an alternative in Chrome.

var link = document.createElement('a');
link.download = "test.png";
link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");;
link.click();

Full code:

<!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>Save Image</title>
	</head>
	<body>
		<h1>Save Image</h1>
		<img src="dynamsoft_logo_black.png" id="img" width="73" height="73" alt="dynamsoft"/>
		<canvas width="73" height="73" id="canvas">canvas</canvas>
		<script type="text/javascript">
			window.onload = function() {
				var canvas = document.getElementById("canvas");
				var ctx = canvas.getContext("2d");
				var img = document.getElementById("img");
				ctx.drawImage(img, 0, 0);
			}
		</script>

		<button type="button" onclick="saveImage()">save image</button>
		<script type="text/javascript">
			function saveImage() {
				var ua = window.navigator.userAgent;

				if (ua.indexOf("Chrome") > 0) {
					// save image without file type
					var canvas = document.getElementById("canvas");
					document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

					// save image as png
					var link = document.createElement('a');
    				link.download = "test.png";
    				link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");;
    				link.click();
				}
				else {
					alert("Please use Chrome");
				}
			}
		</script>
	</body>
</html>

You can download the source code – SaveImage. If you have any questions, please feel free to contact me at {Desmond at Dynamsoft dot com}.

Webcam in HTML5

In the previous blog post, I have glanced at HTML5. Probably many people have already experienced some cool functions of HTML5. In this article, I would like to share how to invoke Webcam in HTML5.

While strolling through StackOverflow, I found there are many questions about how to display webcam in a web browser. Using HTML5, with a few tricks, can manage to show a Webcam in a web browser conveniently.

Please follow this tutorial step by step, and you can instantly build a webcam application in a web browser.

Create a <video> element and two <button> elements

<video id="video"></video>
<button id="start">start</button>
<button id="stop">stop</button>

Initialize

var streaming = false,
video = document.querySelector('#video'),
start = document.querySelector('#start'),
stop = document.querySelector('#stop'),
width = 320,
height = 0;

Get video

navigator.getMedia = (navigator.getUserMedia ||
                                   navigator.webkitGetUserMedia ||
                                   navigator.mozGetUserMedia ||
                                   navigator.msGetUserMedia);
navigator.getMedia(
              {
                  video: true,
                  audio: false
              },
              function (stream) {
                  if (navigator.mozGetUserMedia) {
                      video.mozSrcObject = stream;
                  } else {
                      var vendorURL = window.URL || window.webkitURL;
                      video.src = vendorURL.createObjectURL(stream);
                  }
                  video.play();
              },
              function (err) {
                  console.log("An error occured! " + err);
              }
            );

Resize video

video.addEventListener('canplay', function (ev) {
                if (!streaming) {
                    height = video.videoHeight / (video.videoWidth / width);
                    video.setAttribute('width', width);
                    video.setAttribute('height', height);
                    canvas.setAttribute('width', width);
                    canvas.setAttribute('height', height);
                    streaming = true;
                }
            }, false);

 Start or stop video

start.addEventListener('click', function (ev) {
                video.play();
                ev.preventDefault();
            }, false);
stop.addEventListener('click', function (ev) {
                video.pause();
                ev.preventDefault();
            }, false);

Pretty easy. For further reading, you can refer to Mozilla’s WebRTC docs.

HTML5 is definitely the trend of web technology. However, it is not so mature yet. Browsers are adopting features from HTML5 and evolving themselves over time. In the current stage, considering the compatibility and the security, using a 3rd-party webcam plugin, like ImageCapture Suite, would be a good option, especially if your image capture project has a tight schedule. Besides image acquisition, the plugin also allows you to do simple image processing, HTTP uploading and downloading. ImageCapture Suite supports all the mainstream web browsers like Chrome, IE, Firefox, and Opera on both Mac and Windows platform.

If you have any questions or comments, please leave a message in the comments section below or email me at kgao@dynamsoft.com.

New to HTML5

What is HTML5

HTML5 is a markup language based on HTML 4 and XHTML 1. It’s goal is to support the latest multimedia and be much more readable and understandable by humans and devices. Also, it is dedicated to reducing the dependency on RIA (Rich Internet Application) such as Flash, Silverlight, JavaFX and so forth, providing more handy APIs for strengthening Internet applications. A generic definition of HTML5 is “HTML5 + CSS3 + JS”.

Why HTML5

  • Standard
  • Cross-platform
  • Auto-adapt to the web page
  • Update in real-time
  • No plugin needed
  • Open and free
  • Friendly to search engines

What can HTML5 do

For experiencing what HTML5 can do, here are some amazing HTML5 web pages:

http://spielzeugz.de/html5/liquid-particles.html

http://ghost-hack.com/post/jsexperiments/tunneler/tunneler.html

http://playbiolab.com/

http://bellard.org/jslinux/index.html

Features of HTML5

Semantics

HTML5 defines some new HTML elements, which makes document description much more precise and readable.

semantics

Here are some useful HTML5 elements:

<article> <header> <aside> <hgroup> <figure> <figure> <figcaption> <section> <footer> <time>.

Deprecated elements: <acronym> <applet> <basefont> <big> <center> <dir> <font> <frame> <s> <isindex> <noframes> <frameset> <strike> <tt> <u> and <xmp>

Connectivity

WebSocket

WebSocket provides for full-duplex communication, which makes more possible interaction between client and server, facilitating live content and the creation of real-time games.

websocket

 

Notifications

Website can push notifications to the desktop via the following code.

if (window.webkitNotifications.checkPermission() == 0) {
    var title = 'HTML5 notification',
        text = 'Can you see HTML5 notification?';
    window.webkitNotifications.createNotification('', title, text).show(); 
}

Multimedia

In HTML5, inserting a video or audio is as convenient as inserting an image.

HTML5 video

<audio src="sound.mp3" controls></audio>
<video src="movie.webm" autoplay controls></video>

3D Graphics Effects

Canvas

Dynamically draw something on the web page.

<canvas id="canvas" width="300" height="300"></canvas>
<script>
  var ctx = document.getElementById("canvas").getContext("2d");
  ctx.fillRect(20, 25, 150, 100);

  ctx.beginPath();
  ctx.arc(220, 110, 100, Math.PI * 1/2, Math.PI * 3/2);
  ctx.lineWidth = 15;
  ctx.lineCap = 'round';
  ctx.strokeStyle = 'rgba(255, 127, 0, 0.5)';
  ctx.stroke();
</script>

WebGL

Without needing a plugin, WebGL provides some APIs to render 2D and 3D graphics in the web browser. This website helps you check whether your browser supports WebGL. Here are some amazing WebGL samples.

HTML5 vs Flash

HTML5:

  • No plugin for web browser.
  • Complex
  • Low popularity so far
  • Cross-platform
  • Lacks an engine
  • Free development tools.

Flash:

  • Smooth and stunning
  • Easy to learn
  • High popularity
  • High battery cost
  • Not open
  • Paid development tools

For more specifications, refer to Wikipedia: Comparison of HTML5 and Flash

Please feel free to contact kgao@dynamsoft.com.