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.