HTML5 Video - Capture And Upload Image To Azure Storage

2. June 2013 23:46

ASP.NET Cloud HTML5 Web Azure 

I was exploring Github for some image effects/filters and I found some but still keep exploring and found an interesting plugin called face-detection. This plugin uses HTML5 getUserMedia to use your web camera only if your browser supports it. Unfortunately, IE10 still doesn’t support it. This seems cool to me, so I created a sample application to test it. This sample application will let you preview the video using your web camera and allows you to capture the image from your web camera and upload  it to the Azure storage. The javascript code for the HTML5 video I am using is from David Walsh’s post. Not every browser supports getUserMedia, so if the user is not using the browser which supports getUserMedia then you can show an alert message to the user notifying about the browser incompatibility. Here is the function which will check your browser compatibility for getUserMedia.

function hasGetUserMedia() {
 // Note: Opera is unprefixed.
 return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
 navigator.mozGetUserMedia || navigator.msGetUserMedia);
if (hasGetUserMedia()) {
 // Good to go!
} else {
 alert('getUserMedia() is not supported in your browser');

To know more and explore more what you can do with getUserMedia visit HTML5Rocks. Moving further, I have a normal HTML page where initially I am placing 3 elements on the page. One is a video tag which will show the stream from the web camera attached to your machine or your laptop camera. Second, is the canvas tag which is used to show the image captured from the web camera and the third one is the normal button which will let me capture the image at my will on its click.

<video autoplay id="video" width="640" height="480"></video>
<input id="snap" type="button" value="Click" />
<canvas id="canvas" width="640" height="480"></canvas>

Notice the autoplay property in the video tag. I have set it because I don’t want the video to be frozen as soon as it started. To make the video work I am using David Walsh’s code as it is without any changes.

window.addEventListener("DOMContentLoaded", function () {
    // Grab elements, create settings, etc.
    var canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        video = document.getElementById("video"),
        videoObj = { "video": true },
        errBack = function (error) {
            console.log("Video capture error: ", error.code);
    if (navigator.getUserMedia) { // Standard
        navigator.getUserMedia(videoObj, function (stream) {
            video.src = stream;
        }, errBack);
    } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
        navigator.webkitGetUserMedia(videoObj, function (stream) {
            video.src = window.webkitURL.createObjectURL(stream);
        }, errBack);
    // Trigger photo take
    document.getElementById("snap").addEventListener("click", function () {
        context.drawImage(video, 0, 0, 640, 480);
}, false);

In the above script, you can see that it first checks if the browser or navigator has the getUserMedia support. if you see there are two conditions one for the standard and other one with the webkit prefix. In the end, the click event on the button which will let me capture the image.

When you view the application in the browser, the browser will prompt you whether you want to allow or deny the application to use the web camera.

You cannot run this just by double-clicking the file due to security reasons. You must access the web page from the server itself, either from within the Visual Studio development server, from IIS or by publishing the file on your production server. It can be annoying for many users to grant the access to the camera every time they access the page. You can save the user consent if you are using https. If you plan to stick with http, you will not be able to do this.

Looking in the address bar again, you will notice that the fav icon of the web application, changed to an animated icon. It is a little red dot which keeps on flashing notifying the user that the camera is in use. If you plan to block the access to the camera permanently or temporarily, you can then click the camera icon which is on the right hand side of the address bar.

When you click the icon you will be prompted with options to continue allow the access to the camera or always block the camera. Also if you notice the camera option, you will see that it is showing me two devices or camera attached to the machine. I build this application on my laptop so I am able to the integrated camera which is the front facing camera of my laptop and the second one is the USB camera I have plugged on my laptop’s USB port. I can choose to use any one of these. If you make any changes to these settings and click on done, you will be asked to reload the page.

This is how my web page looks.

The click button is at the bottom right hand side will let me take a snap of the feed coming from my camera. When I click the Click button, the image is captured and show on the canvas we have added on the page. This is my web page after I took the snap from my web camera.

The second image (at the bottom) is the image on the canvas that is snapped from the camera. Now I want to upload the image to my Azure cloud storage. If you look at the address bar, you’ll notice that I have used normal HTML page. It’s you wish if you want to use a simple HTML page or a web form. Both works good. The problem I am going to face with web forms is if I am going to upload the snapped image to my cloud storage or to my server repository, the page will post-back which is not cool at all. So I am going to accomplish it by making an AJAX call. Add a HTML button to your page and on its click event upload the file to the cloud.

I have the image on my canvas, therefore you just cannot retrieve the image Base64 string just like that. I am going to extract the Base64 string of the image from the canvas and pass it as a parameter. The server method will then convert the Base64 string to stream and upload it to the cloud storage. Here is the jQuery AJAX call.

function UploadToCloud() {
    $("#upload").attr('disabled', 'disabled');
    $("#upload").attr("value", "Uploading...");
    var img = canvas.toDataURL('image/jpeg', 0.9).split(',')[1];
        url: "Camera.aspx/Upload",
        type: "POST",
        data: "{ 'image': '" + img + "' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
            alert('Image Uploaded!!');
            $("#upload").attr("value", "Upload");
        error: function () {
            alert("There was some error while uploading Image");
            $("#upload").attr("value", "Upload");

The line 4 in the above script is the one which will get the Base64 string of the image from the canvas. The string is now in the variable named img which I am passing as a parameter to the Upload web method in my code-behind page. You can use web service or handler or maybe a WCF service to handle the request but I am sticking with page methods. Before you can actually make use of the Azure storage, you have to add reference of the Azure Storage library from NuGet. Fire the below NuGet command to add the Azure Storage reference to your application.

Install-Package WindowsAzure.Storage

After the package/assemblies are referenced in your code, add the below namespaces.

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Auth;
using System.IO; //For MemoryStream
using System.Web.Services; //For WebMethod attribute

These all the namespace will help me to connect to my local cloud storage emulator or to my live cloud storage. This is my upload method which will upload the file to my live cloud storage.

public static string Upload(string image)
    string APIKey = "LFuAPbLLyUtFTNIWwR9Tju/v7AApFGDFwSbodLB4xlQ5tBq3Bvq9ToFDrmsZxt3u1/qlAbu0B/RF4eJhpQUchA==";
    string AzureString = "DefaultEndpointsProtocol=https;AccountName=[AccountName];AccountKey=" + APIKey;
    byte[] bytes = Convert.FromBase64String(image);
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureString);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference("img");
    string ImageFileName = RandomString(5) + ".jpg";
    CloudBlockBlob imgBlockBlob = container.GetBlockBlobReference(ImageFileName);
    using (MemoryStream ms = new MemoryStream(bytes))
    return "uploaded";

I have decorated this method with WebMethod attribute. This is necessary as I have to call this method from jQuery/javascript. Also the method should be public static. The AzureString  serves as the connection string for the cloud storage. You have to change the [AccountName] in the connection string to the storage account name. In my case it is propics. The method accepts the Base64 string as a parameter.

Storage is something different than that of the container and therefore I have to create a container which actually holds my images which I upload to the cloud storage. I am not explaining the code completely but it is not that complicate. To upload the file to the storage I must have a file name. The image I get from the canvas is just a Base64 string and does not have a name, so I have to give it a name. I have a random function which will generate the random string which I will be using as a file name for my image file.

//stole from
private static string RandomString(int size)
    Random _rng = new Random();
    char[] buffer = new char[size];
    for (int i = 0; i < size; i++)
        buffer[i] = _chars[_rng.Next(_chars.Length)];
    return new string(buffer);

This is a small function which I stole from Stackoverflow to generate random name for my image file. So this is it and when I click the upload button on my page.

Now if I check my cloud storage I have can see the uploaded files.

This is just a simple example to get you started. You can give some cool effects before you can actually upload the files. If you do a quick search you’ll find plenty of links which will let you give some cool effects to your pictures. I came across a brilliant plugin called filtrr. You should try it and come up with something which is awesome or may be something like Instagram. Hope this help some folks out there.


 No Rating

Attribute Routing In MVC

26. August 2012 14:33


I took a look at Stack Overflow Stack-Exchange Data Explorer that is built in MVC and is open-source application to query the Stack Exchange data dump that is being provided by Stack Exchange team in every month or few. I do have a dump, but I was more curious to know about the application that they built to query the database. And I must admit that I learned tons of things. I came to know the power of Micro-ORM (Dapper) over Entity-Framework (EF) and one more pretty thing that attracted me was the routing mechanism used in the application. I strongly recommend that you check out this tool/application and take a deep dive in the code, lot of things to learn.

Before we start writing the code, we'll take a quick look at a NuGet package AttributeRouting. You can find the source code at GitHub in case if you are interested. The documentation is simple and explains almost every bit of the package. It's incredibly easy.

The NuGet package I am using is for MVC, if you want to do the same with your Web API application then use this package.

To see how easy it is to implement routing in your MVC application. Start Visual Studio and create a new MVC4 (Internet) application and fire up the below NuGet command.

This command just don't install one single package but also some other dependent packages. Here is the output when I fire the above NuGet command:

PM> Install-Package AttributeRouting
Attempting to resolve dependency 'AttributeRouting.Core (≥'.
Attempting to resolve dependency 'AttributeRouting.Core.Web (≥'.
Attempting to resolve dependency 'WebActivator (≥'.
Successfully installed 'AttributeRouting.Core'.
Successfully installed 'AttributeRouting.Core.Web'.
Successfully installed 'WebActivator'.
Successfully installed 'AttributeRouting'.
Successfully added 'AttributeRouting.Core' to MVCAttrRouteTest.
Successfully added 'AttributeRouting.Core.Web' to MVCAttrRouteTest.
Successfully added 'WebActivator' to MVCAttrRouteTest.
Successfully added 'AttributeRouting' to MVCAttrRouteTest.

Now before you make any changes to the web application, hit CTRL+F5. Hover or click on the links which are on the top which are About and Contact. The URL rendered in the address bar is something like this (as what specified in your application Global.asax file).

For About View:


For Contact View:


The Home that we see here is the name of the controller being used. I don't want the name of the controller to be visible to my site visitors or maybe I just want a different name there. Usually, I would have switch to my application Global.asax file and register a new route there. But now I can now control my routes within controller itself. This is pretty cool for and a time saver, as I do not have to avoid working with Global.asax. This is the simplest implementation of AttributeRouting. Below are the 2 Home controller methods About and Contact:

public ActionResult About()
    ViewBag.Message = "Your app description page.";
    return View();

public ActionResult Contact()
    ViewBag.Message = "Your contact page.";
    return View();

There are no changes in the method, only the routing attribute has been added. The URLs for About and Contact are now free from the controller name Home. Now we look at a second condition where I want to have a totally different URL for About view or to be specific I would say I want to have outbound URLs and this will require RouteName property with the routing attribute. This is called Named Routes. I am going to change the URL to /App/AboutMe.

[GET("App/AboutMe", RouteName = "About")]
public ActionResult About()
    ViewBag.Message = "Your app description page.";
    return View();

Working with parameters without routing can lead to very ugly URLs or some un-wanted params in the URLs. Again to have a clean URL we can handle the parameters passed to the controller action. I have added a new view named Welcome (no scaffolding) in the Home controller and added a ViewBag property GreetMessage. When this view is called, it will display a greeting message in a heading. The GreetMessage will hold the name of the person, which is our parameter. Below is our controller action:

public ActionResult Welcome(string Name)
    ViewBag.GreetMessage = "Welcome " + Name;
    return View();

The URL that is rendered on the browser is:

/App/Greet/ is the URL we want to show and Prashant is the parameter is being passed to the Welcome view.

This is it for this tutorial but this is not it. The AttributeRouting package has to offer a lot of things and has a very powerful and easy way of routing. There are very advance topics that are documented at GitHub.

Related Links:

 No Rating

MP3APP - A Web Application To Get Lyrics, Album Name, Album Art and More

29. June 2012 20:53

ASP.NET MVC Utils Web 

I was busy in few of my freelance projects and got a very rough weekends this whole month. But still I get a bit of time to work on my so called in-house project and somehow I was able to get it completed after a bit of testing. The application I built is a simple web application which will allow you to enter artist name and the song name and let you search the lyrics, album art, artist image, album name and album release date. I hope this application help few people out there.

Now, something about the internals and history of the application. I created a windows application 2 years back and thought of porting the same application for the web. For the, web I used ASP.NET MVC 3 with jQuery but the internals of the application remains the same as it was for my windows app. To fetch the lyrics I use LyrDB and WikiLyrics web services and for album art, album name, artist image etc. I used Last.FM web service. I package the whole stuff and what I got is the application which I was running since 2 years on my machine and now the same application is out for you, use it and suggest me something new if you anything in your minds.

I am not yet finished with this application and you'll see more in coming days.

Try out the application here:

 No Rating

Top 3 Ultimate Timepass For Developers

23. April 2012 13:55

Fundoo Web 

We have been programming a lot so we need some time to refresh our minds and get ourselves in a state where our mind processors can start working again more beautifully. When I am pushing myself hard I play 3 games that is on my favorite list. Though I do have many games but these are the 3 games that I play.

The World's Largest Pac-Mac

The legendry dot-eating games Pac-Man. I first played this game on 8-bit Atari console and I remember I used to bet with my firends. We played Pac-Man on a single maze, we don't have many options, but here we have lots and lots of mazes to choose from. The statistics is a section 

Angry Birds

One of the most playable and most addicted games at the moment available on the web. Amazing stages and awesome game play. I have spent numerous amount of effort and time on this game. I have played the offline version of this game, if you don't want to install then play it right here.

Cut The Rope

This game is more or like Angry Birds. Why? If you have played Angry Birds then you must have noticed that in Angry Birds it is not just about hitting the pillars. It's about how you kill the pigs by consuming fewer birds. Cut The Rope is the game initially written in Objective-C and later written in JavaScript by the awesome developers at Zepto Labs. I love playing this game as it allows you think before you make the move.

Currently rated 2.3 by 3 people

Awesome jQuery Image Plugins For Web Developers

22. April 2012 03:42

Jquery Web 

I am not a web developer but still I love working with jQuery, CSS3, HTML5 and other web development frameworks. But as a programmer I love collect code snippets for my ease and store them on the cloud so I can get the access when I am in need and want to save my time while I am writing code. Out of the box I have a list of few image manipulation plugins which seems pretty impressive to me. Let's take a look:

1. Image Carousels

For simple image carousels you can use rcarousel. The plugin is good if you are planning to implement a simple image carousel. If you are looking for some CSS3 taste then take a look at slideshow using jmpress. The transitions effects are awesome.

2. Adipoli jQuery Image Hover Plugin

This is the best image hover plugin I used and available on the web so far. The plugin has to offer you some amazing effects. My favorite is the greyscale and popout, both effects are good if you plan to have a web based gallery.

3. Captify

If you are looking to have a caption for your images, then do that in style. Captify is a plugin let you have pretty image captions for the image. You can have the caption on the image by default or you can show it to the user on mouseover. You can take a look at a little demo here and download it from the GitHub


Want to work with sprites but don't know how to kick off? Don't wait and go to Spritely. Before you download check the gallery examples. In short Spritely allows you to turn your images into a movie. Simply awesome!!

5. jParallax

I will be surprised if you have not heard about this plugin. One of the most amazing and powerful plugin or I should say a library that can make your images speak or work on their own. I am not going to describe what it does, so you have to go and look for yourself. Visit the demo page.

 No Rating