Capture picture on Webpage with Java Backend

In most of the projects we try to capture user’s face on web page. Till recently many projects have been implementing this using either Activex objects or Using Java Plugin’s or some other media plugin’s. With advent of flash and it’s related technologies this and it’s increase in presence over the web flash has become favorite technology to build such application.  Thus making it browser agnostic as compared to ActiveX Objects.

There is a project on web named JPEGCam which is free and opensource which has capability to do that.

http://code.google.com/p/jpegcam/

My effort is to create a java backend to it’s frontend ( Default one comes with php backend). Following example explains my effort

I have created a mavenized application to make it run without any extra server deployment. Here is the description

I’ve created a simple servlet which just capture’s input stream

Stores data in a folder named uploads

Send the file url back to Client to display

Here is the code

package com.linkwithweb.jpegcam;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Ashwin Kumar
 * Servlet implementation class PictureCaptureServlet
 */
public class PictureCaptureServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String fileStoreURL = "";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PictureCaptureServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		fileStoreURL = config.getServletContext().getRealPath("") + "/uploads";
		try {
			File f = new File(fileStoreURL);
			if (!f.exists()) {
				f.mkdirs();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			long time = new Date().getTime();
			
			FileOutputStream fileOutputStream = new FileOutputStream(
					fileStoreURL + "/"+time+".jpg");
			int res;
			while ((res = request.getInputStream().read()) != -1) {
				fileOutputStream.write(res);
			}
			fileOutputStream.close();
			/**
			 * To make sure each url is differeent and not cached added time to tit
			 */
			response.getWriter().append(
					"http://localhost:8080/uploads/" + time
							+ ".jpg");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
	}

}

Below is sample javascript which handles frontend

	<!-- First, include the JPEGCam JavaScript Library -->
	<script type="text/javascript" src="webcam.js"></script>
	
	<!-- Configure a few settings -->
	<script language="JavaScript">
		webcam.set_api_url( '/capture' );
		webcam.set_quality( 90 ); // JPEG quality (1 - 100)
		webcam.set_shutter_sound( true ); // play shutter click sound
	</script>
	
	<!-- Next, write the movie to the page at 320x240 -->
	<script language="JavaScript">
		document.write( webcam.get_html(320, 240) );
	</script>
	<!-- Code to handle the server response (see test.php) -->
	<script language="JavaScript">
		webcam.set_hook( 'onComplete', 'my_completion_handler' );
		
		function take_snapshot() {
			// take snapshot and upload to server
			document.getElementById('upload_results').innerHTML = '<h1>Uploading...</h1>';
			webcam.snap();
		}
		
		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: ' + image_url + '</h3>' + 
					'<img src="' + image_url + '">';
				
				// reset camera for another shot
				webcam.reset();
			}
			else alert("Java Error: " + msg);
		}
	</script>

Now let me paste my pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.linkwithweb.browsercam</groupId>
	<artifactId>JPEGCamIntegration</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>JPEGCamIntegration Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>JPEGCamIntegration</finalName>
		<plugins>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>8.0.0.M2</version>
				<configuration>
					<scanIntervalSeconds>3</scanIntervalSeconds>
				</configuration>
			</plugin>

			<!-- Facilitates downloading source and javadoc in Eclipse -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.8</version>
				<configuration>
					<wtpversion>2.0</wtpversion>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>


			<!-- Ensures we are compiling at 1.6 level -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Here is how you run this and test

mvn jetty:run-exploded

and click this URL

http://localhost:8080

Code has been checked in to following location

http://code.google.com/p/linkwithweb/source/browse/trunk/Utilities/JPEGCamIntegration.rar

Advertisements

22 thoughts on “Capture picture on Webpage with Java Backend

  1. I gone through your example but not getting how does it work?
    you have created servlet and I want to write that directly in jsp page how would I do that?
    And your pom.xml I am not getting that also. we have write that in web.xml or have create a new xml in WEB-INFwith name pom.xml

    and In javscript code you written webcam.set_api_url( ‘/capture’ ); wht is that
    please telll me step by step this example
    please help
    awaiting for reply

  2. I downloaded your raw project file but it seems not working only in page it displays “Uploading….”
    further operation not happening means saving it to server directory and displaying it to webpage.
    please help……….

    • “I downloaded your raw project file but it seems not working only in page it displays “Uploading….”
      further operation not happening means saving it to server directory and displaying it to webpage.
      please help……….”

      I AM FACING THE SAME PROBLEM.. HOW DID YOU SOLVE IT?

  3. THANKS IT WORKED WITH ME NOW.
    BUT ONE QUERY THE CAPTURED IMAGE TO SAVE WITH NAME WHICH IS TIME IN MILLISECOND..I WANT TO STORE IT WITH MY ONE OF FORM FIELD VALUE. HOW WE CAN DO THIS?
    AND SECOND IS :

    fileStoreURL = config.getServletContext().getRealPath(“”) + “/uploads”;
    try {
    File f = new File(fileStoreURL);
    if (!f.exists()) {
    f.mkdirs();
    }
    } catch (Exception e) {
    // TODO: handle exception
    }

    THIS CREATE DIRECTORY UPLOAD BUT IF I WANT TO CREATE DIRECTORIES IN SIDE UPLOAD IF I HOSTED IT ON CENTRAL SERVER AND ALLOW ACCESS TO APPLICATION FROM 5 TERMINAL AND IMAGE CATURED FROM RESPECTIVE TERMINAL SHOULD GO TO RESPECTIVE TERMINAL DIRECTORY LIKE IF I CAPTURED IMAGE FROM TERMINAL 1 THEN IT SHOULD CREATE TERMINAL 1 DIRECTORY INSIDE UPLOAD AND PUT IMAGE IN THAT. SUPPOSE IF I CAPTURED IT FROM TERMINAL 3 THEN IT SHOULD CREATE TERMINAL 3 DIRECTORY IN UPLOAD AND PUT IMAGE IN THAT…

    PLEASE TELL ME….!

    • Never try to save using terminal names… as it will create problem mapping…later .. Ideall you can create folder based on client login for example
      /uploads/{USER_ID}/ … all pictures go under this…

      To pass any paramter you can use the below method
      webcam.set_api_url( ‘/capture’+’?param=’+param1 );

  4. I downloaded your raw project file but it seems not working only in page it displays “Uploading….”
    further operation not happening means saving it to server directory

  5. I have downloaded your code when i click on the Take Snap The Servlet has to be called it is not calling. Please Explain me why it is not happening

  6. Same with Niru and Yatin, the page only displays “Uploading…” and nothing happening after that. Can you help?
    Thanks in advance.

  7. I gone through your example but not getting how does it work?
    you have created servlet and I want to write that directly in jsp page how would I do that?
    And your pom.xml I am not getting that also. we have write that in web.xml or have create a new xml in WEB-INFwith name pom.xml

    and In javscript code you written webcam.set_api_url( ‘/capture’ ); wht is that
    please telll me step by step this example
    please help
    awaiting for reply

  8. hey i had used this code but it seem not working as when it goes on servlet it gives error
    n where do i place pom.xml…
    reply soon

  9. Hi there would you mind letting me know which web host you’re utilizing?
    I’ve loaded your blog in 3 completely different browsers
    and I must say this blog loads a lot quicker then most.

    Can you recommend a good web hosing provider at
    a honest price? Kudos, I appreciate it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s