My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
Instructions  
Introduction and Usage Instructions
Featured, Phase-Implementation, Phase-Deploy
Updated Feb 4, 2010 by jhuck...@gmail.com

Introduction

JPEGCam is a simple, Javascript and Flash library that allows you to enable your users to submit Webcam snapshots to your server in JPEG format. The Flash movie is variable-sized, and has no visible user interface controls. All commands sent to the movie are done so from Javascript, so you can implement your own look & feel on your site, create your own buttons, and tell the Flash movie what to do from your own code.

Requirements

  • Javascript-enabled browser
    • Tested on:
      • Safari 3.0 Mac OS X Leopard
      • Firefox 2.0 Mac OS X Leopard
      • MSIE 6.0, 7.0 Windows XP SP2
      • Firefox 2.0 Windows XP SP2
      • Chrome 0.3 Beta Windows XP SP2
  • Flash Player 9 & 10

Installation

(For a working example, see "test.html" in the htdocs folder.)

First, copy the following files to your web server:

  • webcam.js
  • webcam.swf
  • shutter.mp3

Embedding In Your Page

To use the tool in your page, edit your HTML (or PHP or whatever) and load the JavaScript library:

  <script type="text/javascript" src="webcam.js"></script>

Next, configure a few settings to taste (see APIDocs for all the available API calls you can make):

<script language="JavaScript">
	webcam.set_api_url( 'test.php' );
	webcam.set_quality( 90 ); // JPEG quality (1 - 100)
	webcam.set_shutter_sound( true ); // play shutter click sound
</script>

Next, load the movie into the page. If you want to load the movie immediately, simply use document.write() as shown below. If you are designing a DHTML application, you can call webcam.get_html(...) at any time to dynamically populate a DIV or other element after the page is finished loading.

<script language="JavaScript">
	document.write( webcam.get_html(320, 240) );
</script>

Add some controls for sending commands to the movie (see APIDocs for a complete list of commands).

<br/><form>
	<input type=button value="Configure..." onClick="webcam.configure()">
	&nbsp;&nbsp;&nbsp;
	<input type=button value="Take Snapshot" onClick="webcam.snap()">
</form>

Finally, add some code for handling the server response:

<script language="JavaScript">
	webcam.set_hook( 'onComplete', 'my_callback_function' );
	function my_callback_function(response) {
		alert("Success! PHP returned: " + response);
	}
</script>

That's it! See APIDocs for a complete list of all the available API calls. See the next section for how to write the server-side receiver.

Server Side Code

The Flash movie makes a HTTP POST to your server-side script, using the Content-Type 'image/jpeg'. This is a NON-STANDARD method which is unlike submitting a form from a web page. If you are using PHP, the JPEG data will NOT be in the normal $_POST associative array. Instead, you should read it from the special PHP wrapper: 'php://input'. For example:

  $jpeg_data = file_get_contents('php://input');

You can write this raw, binary JPEG data to a file handle using the PHP function file_put_contents():

$jpeg_data = file_get_contents('php://input');
$filename = "my_file.jpg";
$result = file_put_contents( $filename, $jpeg_data );

Any output from your script is passed back through the Flash movie to the JavaScript code, which in turn passes it to your onComplete callback function.

For example, if you want your script to pass back a URL to the JPEG image, save the file where you want it, and construct a URL to the file. Then simply print the URL to the output like this:

(This assumes you are saving the files to the current working directory)

$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI'])
 	. '/' . $filename;
print "$url\n";

(See "test.php" for a working example.)

FAQ

Q. I cannot see the image from my camera! What am I doing wrong?

A. You probably have to setup the camera device in the Flash Camera settings dialog first. Often Flash doesn't auto-detect the right device.

webcam.configure( 'camera' );

It is always a good idea to provide a "Configure..." button on your page which calls this function, so users can easily get to it.

Q. What is this ugly permission dialog? Can't I just make it remember me?

A. Yes, you certainly can! In the Flash setup dialogs, click on the 2nd icon from the left (i.e. Privacy Settings), and you can click "Allow", then check the "Remember" checkbox.

You can send your users directly to the Privacy config panel by calling:

webcam.configure( 'privacy' );

A cool trick is to detect "new" users (via a cookie) and register an onLoad handler to send them directly to the Privacy settings.

webcam.set_hook( 'onLoad', 'my_load_handler' );
function my_load_handler() {
	if (is_new_user())
		webcam.configure( 'privacy' );
}

Of course, you have to write the is_new_user() function yourself. I no wanna be settin' no cookies on your domain.

Comment by project member jhuck...@gmail.com, Jan 5, 2009

Hey everyone, I just uploaded JPEGCam version 1.0.4, which has some new features and performance improvements.

The library now freezes the webcam image when it submits to the server, and offers optional functions to separately capture and upload the image (so your users can take multiple snapshots, and upload the one that looks best).

Enjoy!

Comment by mrd...@bredband.net, Jan 12, 2009

Works fine. But instead of resolution you may be able to fix a download instead so that the image is saved on the desktop, so maybe http://demo.turnkey-buddy.com/photo_booth/

Comment by lovenal...@gmail.com, Feb 3, 2009

Hi All

Is there any compatibility with Java instead of PHP for saving the image?? I'm working on plugging this into Sakai (www.sakaiproject.org) which is java-based. Classes in java seem not to recognise the content type image/jpeg easily.

Any thoughts?

Comment by iamkar...@gmail.com, Feb 12, 2009

hi there.

would it be possible if we can have the user enter a unique id as the filename for the image through a html text field. so, after clicking "Take Snapshot" button the data from the text field will be used as the filename.

i hope you won't mind me asking. thank you sir.

Gb!

Comment by aswin.ex...@gmail.com, Mar 10, 2009

In java although I might be wrong but if u read the InputStream? from the request and Write it to a file then the image is saved. I have tested it 10-20 times and so far the images are there but still I m not sure. Read the Servlet Specs to be sure

Comment by mark.sto...@gmail.com, Jun 8, 2009

How do I add this to a form? I want to capture a jpg head shot for a form collecting information for an Identification Database. So what I want to do for example is collect things like "Name" "Employee Number" "EMPLOYEE PHOTO" etc. Then POST the info and upload the jpg to the server. It would be great if you could provide an example. Thanks Mark

Comment by mhew...@gmail.com, Jul 16, 2009

For those wanting to use some sort of additional data, you can do it as a GET but changing the API URL. It would be nicer to work as if it were another form field, but this way does work:

Change: webcam.set_api_url( 'test.php' );

to something like:

var personName = document.getElementById('name').value;

var employeeNumber = document.getElementById('employeeNumber').value;

webcam.set_api_url('test.php?name=' + personName + '&employeenumber=' + employeeNumber);

Obviously POSTs are nicer than GETs, but at least it works.

Comment by jmezzal...@gmail.com, Jan 6, 2010

IN JAVA:

public class FotoCapturaServlet? extends HttpServlet? {

protected void doPost(HttpServletRequest? request, HttpServletResponse? response) throws ServletException?, IOException {

int read; int i = 0; byte byteArray = new byte[(int) request.getContentLength()]; while((read=request.getReader().read()) != -1){

byteArray[i++]=(byte) read;
} }

}

Comment by rierar...@gmail.com, Jan 12, 2010

In case anyone wonders how to save the image in ColdFusion?

<cfimage source="#GetHttpRequestData().content#" destination="your-image.jpg" action="write">

Comment by nxel...@gmail.com, Feb 21, 2010

Hi

Help me

I need to use JpegCam?? in my grails project, but when I make a snap, always I have javascript mistake. I don't know if the problem is in test.php, I made a function in my controller and I call this function in javascript:

<script language="JavaScript">
webcam.set_api_url( '/pruebaImages1/foto/webcam' );
webcam.set_swf_url ( '/pruebaImages1/js/webcam/webcam.swf'); webcam.set_shutter_sound(true,'/pruebaImages1/js/webcam/shutter.mp3');
webcam.set_quality( 90 ); // JPEG quality (1 - 100) webcam.set_shutter_sound( true ); // play shutter click sound
</script>

Thanks

Comment by zen2...@gmail.com, Mar 25, 2010

Hi All,

I have included all the code as given above. But I am getting this error "Error: uncaught exception: Error in Actionscript. Use a try/catch block to find error." when I am clicking "Take Snapshot". Please advice me how to overcome this error.

You can see here http://www.site2preview.com/jpegcam/photo.php

Thanks in Advance

Comment by nicktulip, Mar 25, 2010

Zen2nad - how did you fix the error? I see that it works on your site. I am getting the same error here and looking for a fix.

Thanks

Comment by zen2...@gmail.com, Mar 25, 2010

Nick,

I am still getting this issue. :(

Thanks

Comment by jon...@gmail.com, May 19, 2010

I am looking for some classic asp examples to replace the test.php file save sample that will work with the test.html.

Comment by 530...@gmail.com, Jun 9, 2010

Is there a timer?? Like click a button and wait 5 seconds till it snaps...

Comment by azzusai...@gmail.com, Jun 15, 2010

Hi all,

I got the below response on calling webcam.snap(). Can any one please tell me what could be the reason?

FailToSnap?

<html>

<head><title>

Get Snap

</title>

<link href="../App_Themes/Default/spell.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/Default/style.css" type="text/css" rel="stylesheet" /></head>

</html>

Comment by aniisah....@gmail.com, Jul 2, 2010

In grails, to save image:

String filePath = "c:/image.jpg"
InputStream inputStream = request.getInputStream();

OutputStream out=new FileOutputStream (filePath);
byte[] buf = new byte [1024] ;
int len;
while((len=inputStream.read(buf))>0) out.write(buf,0,len);
out.close();
inputStream.close();
Comment by roydel...@gmail.com, Sep 14, 2010

This a good.

QUESTION: How would bring in that image into Flash.

I am writing an App that aloow the visitor to do these 2 things: 1. Snap a picture of themself 2. drap an image of a hat or eye class(png) to see if it fits.

Can set the image name in php file or in the actionscript ?

Thanks

roydell2b@gmail.com

Comment by roydel...@gmail.com, Sep 14, 2010

This a good.

QUESTION: How would bring in that image into Flash.

I am writing an App that aloow the visitor to do these 2 things: 1. Snap a picture of themself 2. drap an image of a hat or eye class(png) to see if it fits.

Can set the image name in php file or in the actionscript ?

Thanks

roydell2b@gmail.com

Comment by hol...@gmail.com, Sep 29, 2010

I have created an ASP file handler:

strFileName = "../usergfx/"&replace(now(),":","-")&".jpg"

a=Request.TotalBytes
b=Request.BinaryRead(a)

set BinaryStream = CreateObject("ADODB.Stream")

  BinaryStream.Type = 1 '// binary data
  BinaryStream.Open
  BinaryStream.Write b
  
  BinaryStream.SaveToFile server.MapPath(strFileName), 2 '// save to disk

  response.write server.MapPath(strFileName) '// output url

set BinaryStream = nothing

And I also found a ASP.NET file handler:

protected void Page_Load(object sender, EventArgs e)
{
    string strFile = "../usergfx/" + DateTime.Now.ToString("dd_MMM_yymmss") + ".jpg";
    FileStream log = new FileStream(Server.MapPath(strFile), FileMode.OpenOrCreate);
    byte[] buffer = new byte[1024];
    int c;
    while ((c = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        log.Write(buffer, 0, c);
    }
    Response.Write(strFile);
    log.Close();
}

source: DaveCS2 @ http://forums.asp.net/t/1487014.aspx

Thanks for a great flash application! :)

Comment by salmansa...@gmail.com, Oct 30, 2010

Hello holm50

I have tried your ASP file handler (copy/paste into test.asp between <% %>), but it creates an Internal Server Error (500).

I also changed the client side code as follows: webcam.set_api_url( 'test.asp' );

I also created a new folder in same folder as test.asp called usergfx and gave windows write permissions to IUSR... and IWAM...

Can you please help?

Comment by gerardof...@gmail.com, Apr 4, 2011

As I make a php value or other value obtained by GET be sent to test.php and from test.php read it with php? This is make me crazy. Any help is appreciated. PS: I already read the comments by mhew ... @ gmail.com, July 16, 2009 in this wiki.

Comment by jeffy.a...@gmail.com, May 6, 2011

anyone had success in safari 5 and internet explorer 8?

Comment by shuky.ka...@gmail.com, Jun 6, 2011

Anyone had any success with storing to appengine's by using blob service? or by any other way?

Comment by assor...@gmail.com, Jul 9, 2011

Thanks very much for plugin! I've done smth with it http://blog.assorium.ru/creations/photo_maker/ Wanna make translate and facebook comments for not russian people

Comment by netituxl...@gmail.com, Aug 15, 2011

How can i Save As the picture to my Desktop instead of Save to Server ?? Thanks in advance

Comment by fredrick...@gmail.com, Oct 6, 2011

Any thoughts on how to check that the client machine is actually equipped with a webcam?

Comment by w...@104house.cc, Nov 5, 2011

my asp code:

n=now()
temp= year(n) & month(n) & day(n) & "-" & hour(n) & minute(n) & second(n)
strFileName = temp&".jpg"
a=Request.TotalBytes
b=Request.BinaryRead(a)

set BinaryStream = CreateObject("ADODB.Stream")

  BinaryStream.Type = 1 '// binary data
  BinaryStream.Open
  BinaryStream.Write b
  
  BinaryStream.SaveToFile server.MapPath(strFileName), 2 '// save to disk

  response.write strFileName '// output url

set BinaryStream = nothing
and test.html:
                function my_completion_handler(msg) {
                        // extract URL out of PHP output
                        //if (msg.match(/(http\:\/\/\S+)/)) {
                                var image_url = RegExp.$1;
                                // show JPEG image in page
                                document.getElementById('upload_results').innerHTML = 
                                        '<h1>Upload Successful!</h1>' + 
                                        '<h3>JPEG URL: ' + msg + '</h3>' + 
                                        '<img src="' + msg + '">';
                                
                                // reset camera for another shot
                                webcam.reset();
                        //}
                        //else alert("ASP Error: " + msg);
                }

It works!!! Thanks for a great flash application! and hol...@gmail.com ^^

Comment by fenyiad...@yahoo.com, Nov 26, 2011

My webcam freezes after I take more than 70 pictures. It will continue to freeze until I restart the computer before it start working again. Any help would be appreciated. Thank you

Comment by nanda.si...@gmail.com, Dec 20, 2011

Hello everyone,

I have a problem with the given example. I didn't do anything just extracted and pasted in server's (apache server) root folder. Initially, it seems working perfectly, I can able to see myself via webcam. The real problem is, when I click "Take Snapshot", it says "Error: Movie not loaded yet".

Will anyone, give a hint or solution to solve this problem?

Comment by mikle.sol, Jan 8, 2012
Comment by paarma.p...@pp.inet.fi, Feb 9, 2012

Hi, thank you very much, fine plugin. I manage to make very functional and usable user image update form to our intranet.

With iHTML the file write requires only:

<iFILE INPUT='i_priv_post' NAME='somename.jpg' OP="write">

Comment by gad.l...@gmail.com, Apr 7, 2012

In what encoding is the binary data sent to the server ? I'm using a different server side and having trouble decoding the POST data. Thanks

Comment by h...@speculum.pt, May 9, 2012

ASP.NET

<script type="text/javascript" src="webcam.js"> 
</script> 

<script language="JavaScript">
    webcam.set_quality(90); // JPEG quality (1 - 100)
    webcam.set_shutter_sound(true); // play shutter click sound
    webcam.set_stealth(true); // enable stealth mode
    webcam.set_hook('onComplete', 'my_callback_function');

    function my_callback_function(msg) {

        if (msg.indexOf("jpg")) {

            var image_url = msg.substring(0, msg.indexOf("jpg") + 3);
            // show JPEG image in page
            document.getElementById('upload_results').innerHTML =
        					'<h5>JPEG URL: ' + image_url + '</h5>' +
        					'<img src="' + image_url + '">';
        }
    }
</script>

C#

        protected void Page_Load(object sender, EventArgs e)
        {
            //check if it is a snapshot
            if (Request.ContentType.Equals("image/jpeg"))
            {

                string strFile = "";
                byte[] buffer = new byte[1024];
                string photofolder = "photofolder/";
                strFile = photofolder + DateTime.Now.ToString("yyyy-MM-dd_hh;mm;ss") + ".jpg";
            

                // save the file
                int c;
                if ((c = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
                {

                    FileStream log = new FileStream(Server.MapPath(strFile), FileMode.OpenOrCreate);
                    log.Write(buffer, 0, c);

                    while ((c = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        log.Write(buffer, 0, c);
                    }
                    log.Close();
                    Response.Write(strFile);
                    Session["lastsaved"] = strFile;
                    this.ButtonDelete.Visible = true;
                }

            }

Sign in to add a comment
Powered by Google Project Hosting