I have an online booking management system that requires images to be captured of the people being booked into the system. I currently have support for uploading the images manually to the website from a local directory on the client machine (a la Facebook, LinkedIn, etc). However, I also need to be able for the client to click a button enabling them to use a camera (webcam or otherwise) hooked up to the client machine to take a snapshot and automatically upload it to the server.
The client environment is Windows based, and my development environment is ASP.Net MVC 3.
Are there any 3rd party ActiveX or Flash controls that can do this?
I found a 3rd party open-source Flash + JavaScript library that made this fairly simple called 'jpegcam'.
The following code is built against Asp.Net MVC 3 (Razor View + T4MVC)
.
Step 1: Include the javascript library
<script type="text/javascript" src="@Url.Content("~/Scripts/jpegcam/htdocs/images.js")"></script>
Step 2: Setup jpegcam and wire up the necessary hooks
<script type="text/javascript">
webcam.set_api_url('@Url.Action(MVC.Images.Snapshot())');
webcam.set_swf_url('@Url.Content("~/Scripts/jpegcam/htdocs/webcam.swf")');
webcam.set_quality(90); // JPEG quality (1-100)
webcam.set_shutter_sound(false, '@Url.Content("~/Scripts/jpegcam/htdocs/shutter.mp3")');
webcam.set_hook('onComplete', 'upload_complete');
document.write(webcam.get_html(320, 240));
function upload() {
webcam.freeze(); // Snapshot the image from the camera
webcam.upload(); // POST the data w/ content type 'image/jpeg'
}
function upload_complete(response) {
var json = jsonParse(response);
if (json.Redirect) {
window.location.replace(json.Redirect);
} else if (json.Error) {
Notifier.Error('Error', json.Error.Message);
webcam.reset();
} else {
Notifier.Error('Error', 'An unknown error has occurred.');
webcam.reset();
}
}
</script>
Note: The webcam.set_api_url()
call sets up the POST url.
Step 3: Wire up the buttons in the view
<p class="actions">
<input id="capture-configure" class="secondary-button" type="button" value="Configure..." onclick="webcam.configure()" />
<input id="capture-submit" class="primary-button" type="button" value="Snap Mugshot" onclick="upload()" />
<span class="alternate">
or <a class="cancel" href="@Url.Action(MVC.Images.View())">Cancel</a>
</span>
</p>
Step 4: Create the controller action to service the POST
[HttpPost]
public virtual ActionResult Snapshot()
{
var image = new System.Web.Helpers.WebImage(Request.InputStream);
// Do fun, amazing things with the jpeg image
return RedirectToAction(MVC.Images.View());
}
Note: System.Web.Helpers.WebImage
is part of the 'microsoft-web-helpers' NuGet package.