Java Web Cam Example using JMF

After long time i have decide to post again about Java web cam which I have  explained before .

Last time i have used video4linux with linux platform but this time I’m going to use Java Media Framework (JMF) with with windows platform.

First you have to instal the JMF into windows you can download it from Oracle website.Next you have to import JMF plugins into your project .

In here I have used netbeans IDE there for you can see some methods which are not useful for jmf but IDE has includes for its source code by itself.

ex

In hare i have created JFrame and load jmf components into JPanel .

Code Example :

This is the code should be in your jframe in here i have not include the codes regarding for creating of jframe.

public class SimpleWebCam extends javax.swing.JFrame {

    CaptureDeviceInfo device;
    MediaLocator ml;
    Player player;
    Component videoScreen;

    public SimpleWebCam() {
        initComponents();
        // path to webcam in windows web cam device is located in here
        String mediaFile = "vfw:Micrsoft WDM Image Capture (Win32):0";

            ml = new MediaLocator(mediaFile);
        try {
            player = Manager.createRealizedPlayer(ml);

            player.start();
            // create video screen to display webcam preview
            videoScreen = player.getVisualComponent();
            videoScreen.setSize(p1.getSize());
            p1.removeAll();
            p1.add(videoScreen, BorderLayout.CENTER);
            p1.repaint();
            p1.revalidate();

            p2.removeAll();
            p2.add(player.getControlPanelComponent());
            p2.repaint();
            p2.revalidate();

        } catch (IOException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoPlayerException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CannotRealizeException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

This is the code part which is should be in your ” Capture ” Button event .


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        try {

            Thread.sleep(100);//wait 10 seconds before capturing photo
        } catch (InterruptedException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        }

            FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");

            Buffer buf = fgc.grabFrame();//grab the current frame on video screen

            BufferToImage btoi = new BufferToImage((VideoFormat) buf.getFormat());

            Image img = btoi.createImage(buf);
            // save image to file
             saveImagetoFile(img, "MyPhoto.jpg");

             new campic(img).setVisible(true);
    }

Method for save captured image in the hard disk (this method calls inside the capture button action performed event )

 private void saveImagetoFile(Image img, String string) {

            int w = img.getWidth(null);
            int h = img.getHeight(null);
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();

            g2.drawImage(img, 0, 0, null);

            g2.dispose();

            String fileType = string.substring(string.indexOf('.') + 1);
        try {
            ImageIO.write(bi, fileType, new File(string));
        } catch (IOException ex) {
            Logger.getLogger(SimpleWebCam.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

I hope you will understand the example you can download complete project file from here
Download Project

Webcam example using Video4Linux – How to capture image using webcam in java

Today i am going to tell you how to developed simple Webcam application for linux using java. If you are using windows you can easily develop using Java Media Framework (JMF). But JMF is not support for Linux there for we have to use external library call Video4Linux4Java (v4l4j).

First of all you have to install v4l4j or else you have to import v4vl4j.jar file to your project .You can get all the instructions to set up v4l4j from the video for linux website.

This is a sample code for accessing webcam , capture image and save it .

Simple Webcam App with capture button

Simple Webcam App with capture button

Saving image

Saving image

 


package MyCam;

import au.edu.jcu.v4l4j.*;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException;
import com.sun.java.swing.plaf.gtk.GTKLookAndFeel;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
*
*
* @author madushanka
*
*/
public class MyCam extends WindowAdapter implements CaptureCallback {

private static int width = 640, height = 480, std = V4L4JConstants.STANDARD_WEBCAM, channel = 0;
private static String device = "/dev/video0"; //getting device this is the path of device
private VideoDevice videoDevice;
private FrameGrabber frameGrabber;
private JLabel label;
private JFrame frame;
private JButton button;
BufferedImage bf;

public static void main(String args[]) throws UnsupportedLookAndFeelException {

UIManager.setLookAndFeel(new GTKLookAndFeel());
new MyCam();

}

public MyCam() {


try {
initFrameGrabber();     // creating frame grabber
} catch (V4L4JException e1) {
System.err.println("Error setting up capture");
e1.printStackTrace();


cleanupCapture();
return;
}


initGUI(); // creating Jframe


try {
frameGrabber.startCapture();   // Starting cam
} catch (V4L4JException e) {
System.err.println("Error starting the capture");
e.printStackTrace();
}
}

private void initFrameGrabber() throws V4L4JException {   // Setting Framegrabber
videoDevice = new VideoDevice(device); // getting the webcam
frameGrabber = videoDevice.getJPEGFrameGrabber(width, height, channel, std, 80);
frameGrabber.setCaptureCallback(this);
width = frameGrabber.getWidth();
height = frameGrabber.getHeight();

}

private void initGUI() {    // setting JFrame
frame = new JFrame();
label = new JLabel();
button = new JButton("Capture");
frame.getContentPane().add(label);
frame.getContentPane().add(button, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(this);
frame.setTitle("WebCam Example");
frame.setVisible(true);
frame.setSize(width, height);
button.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

System.out.println(bf);
try {
ImageIO.write(bf, "png", new File("out.png"));    // saving image
JOptionPane.showMessageDialog(null, "Saved !!!");
} catch (IOException ex) {
Logger.getLogger(MyCam.class.getName()).log(Level.SEVERE, null, ex);
}


}
});
}

// this method is use for turn off cam and release framegrabber and device
private void cleanupCapture() {
try {
frameGrabber.stopCapture();
} catch (StateException ex) {
}


videoDevice.releaseFrameGrabber();
videoDevice.release();
}

@Override
public void exceptionReceived(V4L4JException e) {

e.printStackTrace();
}

// this method is call from startCapture() method
// getting the frame from framegrabber and draw it on JLable to show the user and recycle frame
// again getting frame , showing it , recycle it
@Override
public void nextFrame(VideoFrame frame) {
setImage(frame.getBufferedImage()); // get the captured frame to Buffered Image

label.getGraphics().drawImage(frame.getBufferedImage(), 0, 0, width, height, null);


frame.recycle();

}

public void setImage(BufferedImage b) {
bf = b;
}

public BufferedImage getImage() {
return bf;
}
}



All About EIMS – Educational Institute Management System

I have been working on a project called “EIMS” since last 2 months with my two NIBM colleagues  ( Ravindu Kaluarchchi and Isuru Madushanka). We developed the software for a Software Competition which is conducted by a UCD Alumni Association of Srilanka.

Actually we just wanted to introduced something new thing to the world.So we hardly work on the project during the last two months.

Today I’m glad to say our product won the first award of the Software Competition.There are 40 competitors   After the winning most of the people asked from us what is  “EIMS” ? , And how its different from other solutions ? etc…..

So i created this post for answer the all the questions and Introduced our product to world.

Decision Support Center of EIMS

Decision Support Center of EIMS

What is EIMS ?

EIMS stands for Educational Institute Management System. It is a powerful management information system to easily manage any educational institute.

Actually its not like common management system we target our product for a institutes ,Universities , Schools and Colleges.

But Why EIMS ? and How is it different from other institute management systems ?

EIMS doesn’t use the traditional ways of other management systems . It uses a new approach.
More concentrated toward the lecturers.

But still allows the management to use the traditional ways of a management system.

EIMS is keep track on following areas >>>> >>>>>>>>>>>>>

1. Student Management
2. Exam Management
3. Decision Support and Reporting
4. File Sharing
5. Messaging
6. Hall management
7. Lecture Scheduling
8. Exam Scheduling

What are the Features of EIMS ? 

  • Designed for surface computers.
  • Touch Friendly interfaces.Multi User support.
  • Runs on different platforms.
  • Portable.
  • Easily maintainable.
  • Allows users to easily test the system without installing it ,by running the system from a live CD or a USB.

What are the Benefits ?

  • Lecturers can upload all their files,mark sheets,papers etc. to the server there by saves time and space.
  • Lecturers can access their lecture material from anywhere ,there by saves lecturers from the trouble of caring their lecture material , mal-functioning cd roms ,usb drives.
  • Provides easy messaging between lecturers.
  • Analyzes student , batch progress and displays in a graphical manner so that lecturers and the management can easily make their decisions.
  • Lecturers can easily view their schedules.
  • Easy scheduling system and Hall management

Technology used and the architecture of EIMS

Language         : java
Target platform : desktop ,surface

Technologies used :

  • Java RMI
  • Java persistence
  • Jasper reporting

Database            : mysql

Here is the screen shots of the Overall System >>>>>>>>>>>>>>>>>

Main Screen with the menu on the top

Main Screen with the menu on the top

You can see there is no traditional menu like file , edit ,view ect you have all the desktop to do your own works.

Main Menu

Main Menu

Simple icon style menu easy to use and user friendly.

snapshot2Simple messaging center easy to use and fast.

Lectuer's Desk for easy file sharing

Lecture’s Desk for easy file sharing

This is where lectures can upload their files lecture notes etc….

snapshot5

snapshot6

Easy reporting with EIMS decision support center

We provide an easy tool for your Reporting jobs.

snapshot7

Student search tool of our Student Management System

Our student management system consists of easy tools like this.

snapshot8

Lecture Scheduling with easy interface

We allow user to do scheduling very easily.

snapshot9

Add Shedules its fast and easy

Add Schedules its fast and easy

Screenshot at 2012-12-25 14:19:38

Exam Management with EIMS

This is the place you can manage students exam marks and generate Result sheet very easily.

Screenshot at 2012-12-25 14:20:19

Course Management

 

Student Registration Wizard

Student Registration Wizard

 

Exam Management Center

Exam Management Center

We mange to track exam scheduling also with our Exam Management Center

Screenshot at 2012-12-25 21:32:13

 

Hall Management With EIMS

Hall Management With EIMS

 

Hall Sheduling

Hall Scheduling

Most important part of the Institute is  “Hall Management “.  Solution is our Hall Booking Center

Briefly i have mention above  the overall system features that we have developed for the competition but we are flexible enough for customize and add more features of this product as you wish if you are interest with our product.

Finally I would like to thank all who helped us to success this project.

Fun terminal commands in Linux – part 1

Today i ‘m going to tell you some fun things which we can do using terminal of Linux.
When we talking about Linux its very easy to use and very flexible to use.

Linux is not an advance OS the thing is you have to be genius enough to understand the simplicity.
I will tell you how to write your own shell script to do things very easyly in my future posts.

There are lot of command in linux but here i’m going to tell you about some fun commands in Linux.
This is the first part of my Linux fun commands series.

1. Play Tom and Jerry With Linux

Your mouse pointer become a Jerry so Tom is going to catch it.
Just move your mouse pointer around screen Tom is seeking for you.

Screenshot at 2012-12-07 22:09:58
How to do it >>>>>>>>>>

1) go to terminal and type

               ” sudo apt-get install oneko “

2) after that  type

               ” oneko “

3) Press Ctrl + C to exit

************************************************************************************************************************************

2. Matrix on your terminal

Your can view Matrix of The Matrix movie on your terminal using this method.

Screenshot at 2012-12-07 22:12:53

How to do it >>>>>>>>>>

1) go to terminal and type

            ” sudo apt-get install cmatrix “

2) after that  type

    ” cmatrix “

3) Press Ctrl + C to exit

************************************************************************************************************************************

3. How to draw CowSay “Hello”

Screenshot at 2012-12-07 23:23:49

You may have seen this type of drawings from websites just like Facebook. This is the way to do it.
In here you can add your own text as a message.

How to do it >>>>>>>>>>

1) go to terminal and type

 ” sudo apt-get install cowsay “

2) after that  type

” cowsay your_Own_text “

Note : if you want to change the drawing just type

   ” cowsay -l “

it will show you avalible drawings in the file. just say if you have choose kitty.
If you want use it just type.

” cowsay -f kitty your_Own_text “

Screenshot at 2012-12-07 22:23:33

How to add Background image to a JFrame

Hi i’m today with my second post.
When talking about java swing package JFrame is the most important class for creating GUI but JFrame class does not have direct method to add image to its background.

We can add Images using JLable but the case is JLable is not the container therefor we cannot add any other  component to top of the JLable.

But i have found the method to add Background images to a JFrame and add other components top of the image.
Just like this.

Here is the JFrame

Here is the sample code….


import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
*
* @author madushanka
*/

//Creating extended class of JComponent class

class backImage extends JComponent {

Image i;

//Creating Constructer
public backImage(Image i) {
this.i = i;

}

//Overriding the paintComponent method
@Override
public void paintComponent(Graphics g) {

g.drawImage(i, 0, 0, null);  // Drawing image using drawImage method

}
}

//Creating JFrame
public class MyFrame extends JFrame {

public MyFrame() throws IOException {


// i have set size of JFrame to size of my image there for image will cover all the area of JFrame

this.setSize(500, 333);

this.setTitle("JFrame with Background image");

// read image file in my HardDisk using imageIO and assign it to buffered image reference

BufferedImage bf = ImageIO.read(new File("/home/madushanka/Desktop/myimage.jpg"));

// adding created component to the JFrame using my backImage class


this.setContentPane(new backImage(bf));

//adding other component

JButton b = new JButton("Click");
JTextField tf=new JTextField();


b.setBounds(318, 143, 98, 27);
tf.setBounds(235, 104, 180, 27);

this.add(b);
this.add(tf);
}

public static void main(String[] args) throws IOException {

MyFrame f = new MyFrame();

f.setVisible(true);
}

}

You can use this code inside the NetBeans also……………

Capture the Screen Using Java !!!!

Today i m going to tell you how to capture screen shots using java Robot class.

There are lot of automated things can do using this class such as Control mouse , Keyboard etc…..

This sample code shows you how to capture the screen and save it as a png image………………

package robottest;

import java.awt.Rectangle;

import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/**
*
* @author Madushanka
*/
public class RobotTest {

public static void main(String[] args) throws Exception{

Robot r=new Robot();

Rectangle rectangle=new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

BufferedImage bf=r.createScreenCapture(rectangle);

File file = new File( "screenshot.gif" );

ImageIO.write( bf, "png", file );

}

}