Click here to Skip to main content
15,861,168 members
Articles / Programming Languages / Java

Capture picture on Webpage with Java Backend

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
27 May 2011Apache1 min read 19.1K   1  
How to capture picture on Webpage with Java Backend

In most of the projects, we try to capture the user’s face on the web page. Till recently, many projects have been implementing this using either ActiveX objects or using Java Plugins or some other media plugins. With the advent of flash and its related technologies, this and its increase in presence over the web flash have become favorite technologies to build such applications, thus making it browser agnostic as compared to ActiveX Objects.

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

My effort is to create a Java backend to its frontend (default one comes with PHP backend). The 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 captures the input stream, stores data in a folder named uploads, and send the file URL back to client to display.

Here is the code:

Java
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 different and 
			 * not cached added time to it
			 */
			response.getWriter().append(
					"http://localhost:8080/uploads/" + time
							+ ".jpg");

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

		}
	}
}

Below is a sample JavaScript which handles the frontend:

JavaScript
<!-- 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:

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:

Code has been checked into the following location:


License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


Written By
Chief Technology Officer Northalley
United States United States
A Technology evangelist with no technical language barriers. A strong believer that Simple Sofware Is Perfect Software. A staunch proponent of software / documentation automation in all domain's. And finally a true diciple of Google Search.

Comments and Discussions

 
-- There are no messages in this forum --