Click here to Skip to main content
13,193,551 members (48,744 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

14.9K views
1 bookmarked
Posted 27 May 2011

Capture picture on Webpage with Java Backend

, 27 May 2011
Rate this:
Please Sign up or sign in to vote.
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:

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:

<!--<span class="code-comment"> First, include the JPEGCam JavaScript Library --></span>
<script type="text/javascript" src="webcam.js"></script>

<!--<span class="code-comment"> Configure a few settings --></span>
<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>

<!--<span class="code-comment"> Next, write the movie to the page at 320x240 --></span>
<script language="JavaScript">
    document.write( webcam.get_html(320, 240) );
</script>
<!--<span class="code-comment"> Code to handle the server response (see test.php) --></span>
<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>

			<!--<span class="code-comment"> Facilitates downloading source and javadoc in Eclipse --></span>
			<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>

			<!--<span class="code-comment"> Ensures we are compiling at 1.6 level --></span>
			<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

Share

About the Author

AshwinRayaprolu
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.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171018.2 | Last Updated 27 May 2011
Article Copyright 2011 by AshwinRayaprolu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid