Infolinks In Text Ads

May 4, 2011

Capture image from webcam java code, examples

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.JButton;
import javax.swing.JComponent;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Camagain extends Applet implements ActionListener {

    /**
     *
     */
    private static final long serialVersionUID = -196359544994677518L;
    public static Player player;
    public CaptureDeviceInfo DI;
    public MediaLocator ML;
    public JButton CAPTURE;
    public Buffer BUF;
    public Image img;
    public VideoFormat VF;
    public BufferToImage BtoI;
    public ImagePanel imgpanel;
    public javax.swing.Timer timer = new javax.swing.Timer(200, this); // 200ms is too fast increase it to suit your need

    public void init(){
         purl = getParameter("url");
         url = purl;
        setLayout(new BorderLayout());
        setSize(320, 600);

        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 = new MediaLocator("vfw://0");

        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);
            Thread.sleep(5000);     // this is important, otherwise you may get NPE somewhere, needs polishing ;-)
            timer.start();                // start timer
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    public void executeCapture(Camagain cf) {
        Frame f = new Frame("SwingCapture");
        //camagain cf = new camagain();   // I didn't had 'SwingCapture, so I added camgain.....

        f.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                playerclose();
                //System.exit(0);
            }
        });

        f.add("Center", cf);
        f.pack();
        f.setSize(new Dimension(320, 600));
        f.setVisible(true);
    }
    public static void playerclose() {
        player.close();
        player.deallocate();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JComponent) {
            JComponent c = (JComponent) e.getSource();
            if (c == CAPTURE) {
                actionCapture();  // maoved every thing to new method action()
            }
        } else if (e.getSource() instanceof javax.swing.Timer) {
            action();       // timer event , call action() again
        }
    }

    public void action() {    // your action handler code.....
        // 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
       /* String path = System.getProperty("user.home")+"/xtest.jpg";
        // save image
        saveJPG(img, path);*/

        //webImageShow(path)
        /*System.out.println("Before Alert----");
        try {
            getAppletContext().showDocument
              (new URL("javascript:webImageShow(\"" + path +"\")"));
            }
          catch (MalformedURLException me) { }
         
          System.out.println("After Alert----");*/
    }

    public void actionCapture() {    // your action handler code.....
        // 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
       
        String fileName = System.currentTimeMillis()+".jpg";
       
        String path = System.getProperty("user.home")+"/"+fileName;
       
        // save image
        saveJPG(img, path);
        //upload(path, url);
       
        //Upload upload1 = new Upload(null, path, "http://10.10.0.176:8080/i-hrpro/upload_file.jsp");
        Upload upload1 = new Upload(null, path, url);
        (new Thread(upload1)).start();
       
        //webImageShow(path)
       
       //path = path.replace("\\", "/");
        //System.out.println("Before Alert----" + path);
        try {
            getAppletContext().showDocument
              (new URL("javascript:webImageShow(\"" + fileName +"\")"));
            }
          catch (MalformedURLException me) { }
         
          System.out.println("After Alert----");
    }
    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) {
            super.paint(g);
            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");
        }
    }
   
    String url;
    String purl;
}

Feb 12, 2011

Map.Entry Interface

Map.Entry Interface -
    Map.Entry Interface is used to hold the view of key-value pair from Map.
Map interface has a method entrySet() which returns the Set object that holds the key value pair. You can iterate the key and value from getKey() and getValue().
You can also set value an element by the setValue() method.

List of methods within the Map.Entry Interface -

 boolean equals(Object o) -
         This method is used to compares the specified object with this entry. If both are equal it return true otherwise return false.

 K getKey() -
    This method returns the key of map.

 V getValue() -
    This method returns the value of corresponding to this entry.

 int hashCode() -
    This method is used to return the hash code value for this map entry.

 V setValue(V value) -
    This method is used to set the values at  corresponding the key.


Example -
public class Test {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("1","ram");
        map.put("2","two");
       
        Iterator s = map.entrySet().iterator();
        while(s.hasNext()){
            Map.Entry m = (Map.Entry)s.next();
            System.out.println(m.getKey());
            System.out.println(m.getValue());

        }
    }
}

ListIterator Interface

ListIterator Interface -
    ListIterator Interface is used for traverse list in both direction. You can find previous element by previous() method and next element by next() method. Within the both method ListIterator maintain the cursor position. ListIterator has previousIndex() for checking that List has previous index or not.
     ListIterator Interface extends Iterator Interface. You can also set any new element in the list.

List of methods within the ListIterator Interface -

void add(E e) -
    This method is used to add a given element into the list.

boolean hasNext() -
    This method is used to check the presence of element in the list when traversing the list in the forward direction.

boolean hasPrevious() -
    This method is used to check the presence of element in the list when traversing the list in the reverse direction.

E next() -
    this method is used to return the next element in the list.

int nextIndex() -
    This method is used for return the index of the next element in the list.

E previous() -
          this method is used to return the previous element in the list.

int previousIndex() -
    This method is used for return the index of the previous element in the list.
         
void remove() -
          This method is used for removes element from the list at the cursor position.

void set(E e) -
    This method is used to replace the element at the cursor position.

NavigableSet Interface

NavigableSet Interface -
    NavigableSet Interface is very useful for searching strategics. NavigableSet Interface gives the functionality for closest search mechanism. NavigableSet may search less than, less than or equal, greater than or equal, and greater than through the lower, floor, ceiling, and higher methods.

There is a example -
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.concurrent.ConcurrentSkipListSet;
public class Test {
    public static void main(String[] args) {
            NavigableSet nSet = new ConcurrentSkipListSet();
            nSet.add("A");
            nSet.add("B");
            nSet.add("C");
            nSet.add("D");
            nSet.add("E");
            nSet.add("F");
           
            System.out.println(nSet.ceiling("B"));
            System.out.println(nSet.floor("B"));
            System.out.println(nSet.lower("B"));
            System.out.println(nSet.higher("B"));
            System.out.println("Iterate Descending order");
            Iterator it = nSet.descendingIterator();
            while(it.hasNext())
                System.out.println(it.next());
            System.out.println("Iterate Ascending order");
            Iterator it1 = nSet.iterator();
            while(it1.hasNext())
                System.out.println(it1.next());
    }
}

output will be :
B
B
A
C
Iterate Descending order
F
E
D
C
B
A
Iterate Ascending order
A
B
C
D
E
F
Related Posts Plugin for WordPress, Blogger...