Using jQuery webcam plugin with ASP.NET MVC

I have to use webcam images in one of applications I build and when playing with different components I found free and easy to use Flash and jQuery based webcam component called jQuery webcam plugin. In this posting I will show you how to use jQuery webcam plugin with ASP.NET MVC application to save captured image to server hard disc.

Preparation

Here are some steps to take before writing any ASP.NET code:

  1. Create new ASP.NET MVC application.
  2. Download jQuery webcam plugin and extract it.
  3. Put jquery.webcam.js, jscam.swf and jscam_canvas_only.swf files to Scripts folder of web application.

Now we are ready to go.

Create webcam page

We start with creating default page of web application. I’m using Index view of Home controller.

@{
    ViewBag.Title =
"Index"
;
}
@section scripts
{

   
<script src="@Url.Content("~/Scripts/jquery.webcam.js")">
    </script>
    <script>
        $("#Camera"
).webcam({
             width: 320,
             height: 240,
             mode:
"save"
,
             swffile:
"@Url.Content("~/Scripts/jscam.swf")"
,
             onTick:
function
() { },
             onSave:
function
() {
             },
             onCapture:
function
() {
                 webcam.save(
"@Url.Content("~/Home/Capture")/"
);
             },
             debug:
function
() { },
             onLoad:
function
() { }
         });
    
</script>
}
<h2>Index</h2
>
<
input type="button" value="Shoot!" onclick="webcam.capture();" 
/>
<
div id="Camera"></div
>

We initialize webcam plugin in additional scripts block offered by layout view. To send webcam capture to server we have to use webcam plugin in save mode. onCapture event is the one where we actually give command to send captured image to server. Button with value “Shoot!” is the one we click at right moment.

Saving image to server hard disk

Now let’s save captured image to server hard disk. We add new action called Capture to Home controller. This action reads image from input stream, converts it from hex dump to byte array and then saves the result to disk.

Credits for String_To_Bytes2() method that I quickly borrowed go to Kenneth Scott and his blog posting Convert Hex String to Byte Array and Vice-Versa.

public class HomeController : Controller
{
   
public ActionResult
Index()
    {
       
return
View();
    }

   
public void
Capture()
    {
       
var
stream = Request.InputStream;
       
string
dump;

       
using (var reader = new StreamReader
(stream))
            dump = reader.ReadToEnd();

       
var path = Server.MapPath("~/test.jpg"
);
        System.IO.
File
.WriteAllBytes(path, String_To_Bytes2(dump));
    }

   
private byte[] String_To_Bytes2(string
strInput)
    {
       
int
numBytes = (strInput.Length) / 2;
       
byte[] bytes = new byte
[numBytes];

       
for (int
x = 0; x < numBytes; ++x)
        {
            bytes[x] =
Convert
.ToByte(strInput.Substring(x * 2, 2), 16);
        }

       
return bytes;
    }
}

Before running the code make sure you can write files to disk. Otherwise nasty access denied errors will come.

Testing application

Now let’s run the application and see what happens.

You need Flash to make webcam work

Whoops… we have to give permission to use webcam and microphone to Flash before we can use webcam. Okay, it is for our security.

After clicking Allow I was able to see picture that was forgot to protect with security message.

And webcam works ...

This tired hacker in dark room is actually me, so it seems like JQuery webcam plugin works okay :)

Conclusion

jQuery webcam plugin is simple and easy to use plugin that brings basic webcam functionalities to your web application. It was pretty easy to get it working and to get image from webcam to server hard disk. On ASP.NET side we needed simple hex dump conversion to make hex dump sent by webcam plugin to byte array before saving it as JPG-file.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    36 thoughts on “Using jQuery webcam plugin with ASP.NET MVC

    • May 16, 2014 at 4:50 am
      Permalink

      Dear admin,

      its working fine for all types of camera but not in smi grabber type , kindly help on this ..

      thanks in advance,
      Jayakumar

    • March 22, 2016 at 2:44 pm
      Permalink

      Dear Admin

      How to set the rear camera setting to take the picture.

      Thanks in advance
      Vishal

    • March 27, 2016 at 1:19 am
      Permalink

      You can set what Flash allows you to set. You can’t switch between front and rear camera through web page AFAIK.

    • November 4, 2016 at 9:23 am
      Permalink

      My self Tapas, from India.I did it. It is working. But in my lenovo Tablet It is not working. is there any solution please tell me as soon as possible.

    • November 6, 2016 at 9:48 pm
      Permalink

      This plugin uses Flash and your browser must have Flash installed and allowed. If this condition is met but it still doesn’t work then please see if browser’s developers tools show any console output or exceptions.

    • May 31, 2017 at 8:31 am
      Permalink

      Hi Gunnar have you tried to do it in .Net Core?

      It’s not possible to use Request.InputStream. Can you help me with it?

    • May 31, 2017 at 9:02 am
      Permalink

      ASP.NET Core has Request.Body property that is stream you can read.

    • February 17, 2024 at 1:48 pm
      Permalink

      this will work in 2024?

    • May 24, 2025 at 4:01 am
      Permalink

      Ademas, cuenta con una seccion de casino con juegos como tragamonedas que garantizan horas de ocio.
      Todo esto respaldado por sistemas de seguridad de ultima generacion y un servicio de atencion al cliente disponible
      las 24 horas. Si estas en Peru y te apasionan las jugadas,
      ahora tienes acceso a una plataforma confiable y moderna como betsafe peru.

      Esta pagina esta disenada para ofrecer una experiencia local adaptada al mercado peruano, con cuotas competitivas
      y metodos de pago nacionales.

    • June 5, 2025 at 11:59 pm
      Permalink

      gunnarpeipman.com
      gunnarpeipman.com

    • July 18, 2025 at 3:17 pm
      Permalink

      Desde então, tenho me apaixonado cada vez mais pela diversidade de temas e pela complexidade do assunto. A cada texto, sinto que aprendo algo novo, seja sobre as nuances do mercado de apostas, suas regulamentações ou os diferentes tipos de esportes que dominam as plataformas de apostas. A possibilidade de explorar uma variedade tão grande de tópicos e manter o foco no engajamento do leitor tem sido uma experiência enriquecedora e desafiadora. O programa VIP do Pin-Up Casino fira em torno de Pincoins (PNC). Os jogadores ganham Pincoins a cada depósito efetuado, e por completarem diversas tarefas listadas no site do cassino. Essas tarefas podem ser feitas de uma vez (verificar a conta do jogador) ou diariamente, como jogar num determinado número de caça-níqueis diferentes em 24 horas.
      https://suporte.saj.ba.gov.br/jogo-da-bombinha-para-2-jogadores-cooperacao-e-estrategia-no-campo-minado-online-3/
      For the new players of Sweet Bonanza 1000, merely load the game and set the price that you can afford to pay per spin. The cost of what is your bet can start as low as $0.20, with prices then rising to a max bet amount of $240 ($300 with Ante Bet). The more you pay, the greater the return when you win, and with your bet set, press the spin or autoplay button to start the game. Sweet Bonanza 1000 is very much a been there, done that kind of game. It offers very little, but I still gave it a chance. I decided to play 50 spins with my bet set at $2 per spin. And BOOM, we are off to a great start, landing $28 within my first ten spins. After that, a lot of consecutive wins form by the Tumbler mechanics. With 29 spins left, I am breaking even. That said, with my last 15 spins, the game goes quiet, and landing wins is less frequent. With my last five spins, a flurry of wins totaling $5.80 sees me fall $10, which is sort of breaking even. Not a bad experience, really.

    • July 22, 2025 at 7:21 am
      Permalink

      Modern encryption technologies ensure the safety of personal information and financial data of players. All financial transactions are processed through reliable and secure channels, which minimizes the risk of fraud. Space XY supports the principles of responsible gaming, offering players tools to manage their spending and playing time. You can set betting limits, as well as receive tips on safe gaming. Playing Space XY and other crash games is legal so long as online gambling is legal wherever you are. If you’re in a location where online gambling is illegal, it’s best not to play. BGaming started the year 2022 with some experiments. The company delivered Space XY, the first-of-its-kind crash game in the vendor’s portfolio. In a nutshell, this type is aimed at cryptocurrency gamblers and players have to launch the rocket over X and Y coordinates and predict the best time to jump off the rocket before it disappears. It’s going to be an innovative blast!
      https://bosmedali.com/dragon-tiger-game-review-best-app-with-lowest-minimum-deposit-in-india/
      If you’re playing solo, it’s by far the most important purchase you’ll make early on, because its good stats and that crane mean it’s ideal to handle the vast majority of haulage jobs the game gives you. There is a point where some loads start to get a bit too heavy for it to deal with easily, but I’ve made it up to level 12 so far and it’s still the heart of my fleet. That arguably exposes a bit of a flaw in RoadCraft’s launch vehicle offerings – there’s only one or very occasionally two better successors you can unlock for each of the different vehicle types as you progress. RNG methods- If you intend to play Chicken Road, you must be sure that the chosen casino platform offers a Random Number Generator, which promises the player the fair game.

    Leave a Reply

    Your email address will not be published. Required fields are marked *