JMF Webcam app with saving JPEG

4 Comments

Since so many people ask for this code, but never get it, I figured I’d repost it. I didn’t write it, but I added the jpeg saving part, and modified it for my device, which you will have to do to get it to work. Just go into JMFRegistry and get the device name from your webcam and then edit the code. Also, keep in mind that some webcams don’t work with JMF. You have to have a webcam that supports VFW or WDM interface.
And here’s the code:

import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import javax.media.protocol.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;
 
public class SwingCapture extends Panel implements ActionListener 
{
  public static Player player = null;
  public CaptureDeviceInfo di = null;
  public MediaLocator ml = null;
  public JButton capture = null;
  public Buffer buf = null;
  public Image img = null;
  public VideoFormat vf = null;
  public BufferToImage btoi = null;
  public ImagePanel imgpanel = null;
  
  public SwingCapture() 
  {
    setLayout(new BorderLayout());
    setSize(320,550);
    
    imgpanel = new ImagePanel();
    capture = new JButton("Capture");
    capture.addActionListener(this);
    
    String str1 = "vfw:Logitech USB Video Camera:0";
    String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
    di = CaptureDeviceManager.getDevice(str2);
    ml = di.getLocator();
    
    try 
    {
      player = Manager.createRealizedPlayer(ml);
      player.start();
      Component comp;
      
      if ((comp = player.getVisualComponent()) != null)
      {
        add(comp,BorderLayout.NORTH);
      }
      add(capture,BorderLayout.CENTER);
      add(imgpanel,BorderLayout.SOUTH);
    } 
    catch (Exception e) 
    {
      e.printStackTrace();
    }
  }
 
 
  
  public static void main(String[] args) 
  {
    Frame f = new Frame("SwingCapture");
    SwingCapture cf = new SwingCapture();
    
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
      playerclose();
      System.exit(0);}});
    
    f.add("Center",cf);
    f.pack();
    f.setSize(new Dimension(320,550));
    f.setVisible(true);
  }
  
  
  public static void playerclose() 
  {
    player.close();
    player.deallocate();
  }
  
 
  public void actionPerformed(ActionEvent e) 
  {
    JComponent c = (JComponent) e.getSource();
    
    if (c == capture) 
    {
      // Grab a frame
      FrameGrabbingControl fgc = (FrameGrabbingControl)
      player.getControl("javax.media.control.FrameGrabbingControl");
      buf = fgc.grabFrame();
      
      // Convert it to an image
      btoi = new BufferToImage((VideoFormat)buf.getFormat());
      img = btoi.createImage(buf);
      
      // show the image
      imgpanel.setImage(img);
      
      // save image
      saveJPG(img,"c:\\test.jpg");
    }
  }
  
  class ImagePanel extends Panel 
  {
    public Image myimg = null;
    
    public ImagePanel() 
    {
      setLayout(null);
      setSize(320,240);
    }
    
    public void setImage(Image img) 
    {
      this.myimg = img;
      repaint();
    }
    
    public void paint(Graphics g) 
    {
      if (myimg != null) 
      {
        g.drawImage(myimg, 0, 0, this);
      }
    }
  }
  
 
  public static void saveJPG(Image img, String s)
  {
    BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage(img, null, null);
 
    FileOutputStream out = null;
    try
    { 
      out = new FileOutputStream(s); 
    }
    catch (java.io.FileNotFoundException io)
    { 
      System.out.println("File Not Found"); 
    }
    
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
    param.setQuality(0.5f,false);
    encoder.setJPEGEncodeParam(param);
    
    try 
    { 
      encoder.encode(bi); 
      out.close(); 
    }
    catch (java.io.IOException io) 
    {
      System.out.println("IOException"); 
    }
  }
  
}

More detail

Advertisements

Date picker built-in Java 7 (SwingX)

Leave a comment

JXDatePicker is a date picker that is built-in class in SwingX in JDK7.
Here is snippet code of JXDatePicker:

final JLabel label = new JLabel();
label.setText("Choose Date by selecting below.");
 
final JXDatePicker datePicker = new JXDatePicker(System.currentTimeMillis());
datePicker.addActionListener(new ActionListener() {
	public void actionPerformed(ActionEvent e) {
		label.setText(datePicker.getDate().toString());
	}
});
 
 
frame.getContentPane().add(label, BorderLayout.NORTH);
frame.getContentPane().add(datePicker, BorderLayout.CENTER);

Test performance in Java

Leave a comment

Here is the good website for me to make a performance test in Java
Click here to visit the site.

Consuming a REST Web Service

Leave a comment

PROBLEM
Representation State Transfer (REST) is a lite-weight approach for communicating with other applications using HTTP and XML. While SOAP let’s you define your own operations, with REST services there are essentially only four operations: GET, POST, PUT and DELETE. Given it’s simplicity, REST services are becoming very popular building block on web applications.

SOLUTION
Since REST focusses on HTTP and XML, there isn’t a need for any specialized java libraries for accessing REST services. The JAVA platform already has the basic libraries in place for handling HTTP requests (java.net.* or org.apache.commons.httpclient.*) and processing XML (JAXP). Therefore nothing additional is required.

As far as consuming REST services from Spring applications, and in particular applications produced with Skyway Builder, the standard HTTP and XML processing logic available to java developers can be used. A developer can write java code and/or Spring beans for making the REST calls and processing the results. Additionaly a developer can leverage the Groovy support in Skyway.

HOW IT WORKS
Here’s an example java class that calls a REST service using Apache commons httpclient library.

Sample java code invoking REST services

/*
 * SampleWebServiceGet.java
 *
 * Created on September 12, 2009, 12:33 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package javaapplicationsimpletest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 *
 * @author Seven
 */
public class SampleWebServiceGet {
    
    public String callRestService(String request) throws IOException {
        
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(request);        
        
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        
        // Send GET request
        int statusCode = client.executeMethod(method);
        
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }
        
        byte[] responseBody = method.getResponseBody();
        
        return new String(responseBody);
    }
    
}


Note:
We need download “commons-httpclient, commons-logging, commons-codec” from apache.org

Make HTTP POST or GET Request from Java

Leave a comment

Here is the sample that address about make HTTP Post or Get Request from Java.

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

public class HTTPRequestPoster
{
/**
* Sends an HTTP GET request to a url
*
* @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
* @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
* @return - The response from the end point
*/
public static String sendGetRequest(String endpoint, String requestParameters)
{
String result = null;
if (endpoint.startsWith("http://"))
{
// Send a GET request to the servlet
try
{
// Construct data
StringBuffer data = new StringBuffer();

// Send data
String urlStr = endpoint;
if (requestParameters != null && requestParameters.length () > 0)
{
urlStr += "?" + requestParameters;
}
URL url = new URL(urlStr);
URLConnection conn = url.openConnection ();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
result = sb.toString();
} catch (Exception e)
{
e.printStackTrace();
}
}
return result;
}

/**
* Reads data from the data reader and posts it to a server via POST request.
* data - The data you want to send
* endpoint - The server's address
* output - writes the server's response to output
* @throws Exception
*/
public static void postData(Reader data, URL endpoint, Writer output) throws Exception
{
HttpURLConnection urlc = null;
try
{
urlc = (HttpURLConnection) endpoint.openConnection();
try
{
urlc.setRequestMethod("POST");
} catch (ProtocolException e)
{
throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
}
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

OutputStream out = urlc.getOutputStream();

try
{
Writer writer = new OutputStreamWriter(out, "UTF-8");
pipe(data, writer);
writer.close();
} catch (IOException e)
{
throw new Exception("IOException while posting data", e);
} finally
{
if (out != null)
out.close();
}

InputStream in = urlc.getInputStream();
try
{
Reader reader = new InputStreamReader(in);
pipe(reader, output);
reader.close();
} catch (IOException e)
{
throw new Exception("IOException while reading response", e);
} finally
{
if (in != null)
in.close();
}

} catch (IOException e)
{
throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
} finally
{
if (urlc != null)
urlc.disconnect();
}
}

/**
* Pipes everything from the reader to the writer via a buffer
*/
private static void pipe(Reader reader, Writer writer) throws IOException
{
char[] buf = new char[1024];
int read = 0;
while ((read = reader.read(buf)) >= 0)
{
writer.write(buf, 0, read);
}
writer.flush();
}

}

Testing in Java

Leave a comment

Abstract Class Vs Interface in Java

Leave a comment

Now I would like to make introduction about the difference between Abstract Class and Interface in Java.
For Abstract Class may contains abstract method and abstract property, but Interface may contains only normal method without encapsulation and no method body implementation.
We use abstract class and interface as base class in Java.

 //Abstarct Class
public abstract class Entity {
private int id;
private Color c;
public void setID(int id) { this.id = id }
public int getID() { return id; }
public void setColor(Color c) { this.c = c; }
public Color getColor() { return c; }
public abstract void paint(Graphics g);
}

//Interface

public interface Entity {
void setID(int id) ;
int getID();
void setColor(Color c);
Color getColor() ;
void paint(Graphics g);
}

Older Entries