Publié le 01/02/2011
Auteur fobec
Réseaux sociaux
0 partages
0 tweets
0 plus
6 commentaires

Prendre une photo a partir d'une webcam

Après avoir installé le Framework JMF 2.1, voici un exemple pour capturer une image à partir de la webcam. Ainsi la caméra est utilisée comme un appareil photo numérique dont nous allons transférer une image vers un fichier.
webcam_1068

Enregistrer une photo à partir d'une Webcam

L'application capture le flux d'une cam et l'affiche en continue sur un JFrame. Le bouton Capture permet de prendre une copie de l'image en cours et l'enregistre au format JPEG sous C:test.jpg.

A droite, une copie d'écran de ma tasse requin prise à partir d'un webcam Microsoft :)

Pour faire fonctionner JMF, ne pas oublier de lier les JAR JMF au projet. Sous NetBeans, suivre les étapes suivantes:
- click droit sur le nom du projet,
- propriétés
- ajouter les jar à partir de la fenêtre Librairie



/**
 *
 * @author found on the web
 */
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 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 WebcamCapture 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 WebcamCapture() {
        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 = 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);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        Frame f = new Frame("Webcam Capture");
        WebcamCapture cf = new WebcamCapture();
 
        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(1.0f, false);
        encoder.setJPEGEncodeParam(param);
 
        try {
            encoder.encode(bi);
            out.close();
        } catch (java.io.IOException io) {
            System.out.println("IOException");
        }
    }
}

Ajouter un commentaire

Les champs marqués d'un * sont obligatoires, les adresses emails se sont pas publiées.
avatar pacman

Publié par pacman

le 29/04/2011 à 17:00:25

thanks for sharing, that s great!

avatar space

Publié par space

le 31/05/2011 à 16:17:36

peut on avoir un meme code pour linux

avatar math

Publié par math

le 20/01/2012 à 16:28:24

Salut, quelle est la modification a faire pour pouvoir utiliser une webcam usb qui n'est pas une logitech?

avatar need help

Publié par need help

le 15/04/2012 à 03:55:27

Merci pour cet exemple.
Est ce possible de récupérer le flux video d'une camera ou bien une appareil photo branché par USB.

Merci d'avance.

avatar MasterMbg

Publié par MasterMbg

le 06/03/2013 à 16:34:53

Salut! merci pour le code, si tu y ajoutais des commentaires avant chaque module ce serait encore plus facilitant! merci infiniment...

avatar medfayz

Publié par medfayz

le 10/04/2013 à 17:29:34

hi everybody thanks for the code , and please can any one help me to fix that exception.
javax.media.NoPlayerException: Cannot find a Player for :vfw:0

thanks

A lire aussi

Réseaux sociaux
Présentation de l'article
Catégorie
java - class
Mise a jour
01/02/2011
Visualisation
vu 10724 fois
Public
Internaute
Auteur de la publication
Fobec
Admin
Auteur de 267 articles
|BIO_PSEUDO|
Commentaires récents

Publié par Elvine dans java

Bonsoir, je voudrais savoir si ce code peut etre utilise avec Netbeans

Publié par hozin2003 dans CMS

merci, c'est mon problème et voila j'ai trouvé la solution merci et voila un bon pas pour un débutant

Publié par Tom dans java

Hello!
Cependant, mon Eclipse ne reconnait pas HttpLoader comme type valide...
Comment faire pour que ca marc...

Publié par fobec dans logiciel

MAJ: migration vers GoogleMap V3 de la carte

Publié par lamardiallo48 dans java

trop bon ton code ca m'a beaucoup aide. Merci