Wednesday, July 30, 2008

Tutorial: grab images from a network camera using Java

Requirements: a network camera with a web interface. The web interface should make available somehow a dynamically generated JPEG image. For the implementation we will use the Apache commons, available here. In particular we need the http-commons-client, the commons-logging and the commons-codec. The http-commons-client is what we really need, the other two packages are dependencies for the commons-client.

To run the program you need to have the JAR files included in the tar.gz archives in the Java classpath.

First of all we need to know the URL to get the image from the camera. In my case it was something like http://xxx.yyy.www.zzz/cgi-bin/video.jpg?size=3. Now we are ready to write the code.
//NetworkCamera class

import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class NetworkCamera
{
    public NetworkCamera (String url)
    {
        log ("Registered network camera. Image url = " + url);
        _method = new GetMethod(url);
        //Create the HTTP client and set the parameters
        _client = new HttpClient();
        _client.getParams().setParameter ("http.useragent", "CustomizedJavaClient");
        _client.getParams().setParameter ("http.connection.timeout", new Integer(5000));
        _method.setFollowRedirects (true);
    }
    
    
    public byte[] getImage ()
    {
        log ("Getting image...");
        byte[] image = null;
        try {
            int retCode = _client.executeMethod (_method);
            if ( retCode != -1){
                log ("getMethod succeed [HTTP-RESPONSE-CODE" + retCode + "]. Content lenght = " + _method.getResponseContentLength());
                //The HTTP response body contain the bytes of the image
                image = _method.getResponseBody();
                System.out.println ("Bytes read: " + image.length);
            }
        }
        catch (IOException ex) {
            //Report error
            System.out.println (ex.getMessage ());
        }  
        return image;
    }
    
    private void log (String message)
    {
        if (DEBUG) {
            System.out.println (message);
        }
    }
    

    private GetMethod _method;
    private HttpClient _client;
    
    private static final boolean DEBUG = true;
}

//Main class (for test purpose)

import java.io.FileOutputStream;

public class Main
{
    public static void main (String[] args) throws Exception
    {
        Camera cam = new NetworkCamera (CAMERA_IMAGE_URL);
        byte[] image = cam.getImage();
        
        FileOutputStream fos = new FileOutputStream (IMAGE_FILE_NAME);
        fos.write(image);
        fos.close();
    }
    
    private static final String CAMERA_IMAGE_URL = "http://xxx.yyy.www.zzz/cgi-bin/video.jpg?size=3";
    private static final String IMAGE_FILE_NAME = "test.jpg";
}

The code gets a frame from the camera as a JPEG file and saves it as test.jpg.
Of course you may use exactly the same code to grab an image from a web site. You can try, for instance, to assign
private static final String CAMERA_IMAGE_URL = "http://www.google.com/intl/en_ALL/images/logo.gif"
and see what happens.

Thursday, July 24, 2008

Object to byte array and byte array to Object in Java

Here how to convert an Object to a byte array, and vice-versa.
public byte[] toByteArray (Object obj)
{
  byte[] bytes = null;
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  try {
    ObjectOutputStream oos = new ObjectOutputStream(bos); 
    oos.writeObject(obj);
    oos.flush(); 
    oos.close(); 
    bos.close();
    bytes = bos.toByteArray ();
  }
  catch (IOException ex) {
    //TODO: Handle the exception
  }
  return bytes;
}
    
public Object toObject (byte[] bytes)
{
  Object obj = null;
  try {
    ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
    ObjectInputStream ois = new ObjectInputStream (bis);
    obj = ois.readObject();
  }
  catch (IOException ex) {
    //TODO: Handle the exception
  }
  catch (ClassNotFoundException ex) {
    //TODO: Handle the exception
  }
  return obj;
}

Tuesday, July 22, 2008

Extract EXIF Metadata from JPEG files using Java

I was looking into this problem for a project I am working on, and I found this cool library.


Here some usage examples.

Sunday, July 20, 2008

Blogger Hacks

The first thing I wanted to do as soon as I created this blog was to remove the blogger bar on top of the pages.

I googled for a while and I found the solution in here. The hack is really simple, you have just to insert a new CSS rule just before the "Variable definitions" in the HTML code of your template:
#navbar-iframe
{
display: none !important;
}
The !important keyword prevent the property from being overwritten from the rules inserted by the blogger engine.

Thursday, July 17, 2008

UDP Server Socket using Java

The following simple example shows how to open a UDP server socket using Java. The code receives strings from a UDP socket and print them in the standard output.
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.DatagramPacket;

public class SimpleUDPSSocket extends Thread
{
public SimpleUDPSSocket() throws Exception
{
_dSocket = new DatagramSocket(PORT);
_running = false;
}

public void run()
{
byte buf[] = new byte[MAX_SIZE];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
String data;
_running = true;
while (_running) {
try {
_dSocket.receive (packet);
}
catch (Exception ex) {
_running = false;
break;
}
data = new String(packet.getData(), 0, packet.getLength());
System.out.println (data);
}
}

private DatagramSocket _dSocket;
private boolean _running;
private static final int PORT = 4444;
private static final int MAX_SIZE = 64;
}