WebCam no swing

7 respostas
W

Olá a todos deste forum,

Eu tenho uma aplicacão em swing que captura uma imagem da WebCam, qaundo eu chamo novamente o frame ele me traz o seguinte erro:

init:
deps-jar:
compile-single:
run-single:
java.io.IOException: Could not connect to capture device

An unexpected error has been detected by Java Runtime Environment:

EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x03a915cb, pid=5064, tid=4636

Java VM: Java HotSpot™ Client VM (10.0-b23 mixed mode, sharing windows-x86)

Problematic frame:

C [p1110vfw.dll+0x15cb]

An error report file with more information is saved as:

C:\workspace_NetBeans\gestao&cadastro\hs_err_pid5064.log

If you would like to submit a bug report, please visit:

http://java.sun.com/webapps/bugreport/crash.jsp

The crash happened outside the Java Virtual Machine in native code.

See problematic frame for where to report the bug.

Java Result: 1
CONSTRUÍDO COM SUCESSO (tempo total: 4 segundos)

esse erro aparece quando eu fecho o frame e tento abrir novamente atraves de um jbutton, quando eu fecho a IDE netbeans 6.5.1 e abro novamente, ele volta ao normal quando eu clico no button

Eu sou novato em java(swing), se alguem puder me ajudar eu agradeço.

7 Respostas

M

[color=darkblue]O que você usa nessa sua aplicação ? [/color]

Download JMF

JMF Tutorial

W

Eu estou usando uma tela de cadastro de pessoas e tem um jbutton(Tirar Foto), quando eu clico no mesmo ele abre um jframe(CapturaFoto) que possui um jpanel interno detro do CapturaFoto, esta funcionando ok a imagem da webcam está sendo reproduzida. O problema e quando eu estou fechando esse jframe atraves do jbutton(fechar) ou da forma traticional fechar no X, quando eu clico novamente para Tirar Foto conforme relatei acima e lança esse erro:

14/07/2009 11:13:00 Assunto: WebCam no swing


Olá a todos deste forum,

Eu tenho uma aplicacão em swing que captura uma imagem da WebCam, qaundo eu chamo novamente o frame ele me traz o seguinte erro:

init:
deps-jar:
compile-single:
run-single:
java.io.IOException: Could not connect to capture device

An unexpected error has been detected by Java Runtime Environment:

EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x03a915cb, pid=5064, tid=4636

Java VM: Java HotSpot™ Client VM (10.0-b23 mixed mode, sharing windows-x86)

Problematic frame:

C [p1110vfw.dll+0x15cb]

An error report file with more information is saved as:

C:\workspace_NetBeans\gestao&cadastro\hs_err_pid5064.log

If you would like to submit a bug report, please visit:

http://java.sun.com/webapps/bugreport/crash.jsp

The crash happened outside the Java Virtual Machine in native code.

See problematic frame for where to report the bug.

Java Result: 1
CONSTRUÍDO COM SUCESSO (tempo total: 4 segundos)

Eu estou usando o JDK 1.6.0_07
IDE NetBeans IDE 6.5.1 (Build 200903060201)

detalhe quando eu fecho a IDE, Inicio ela novamente e rodo a aplicação e faço todos os processo citados acima funciona
Eu acho que devo fazer um método para fechar a conexão da JVM com driver da WebCam o que vc acha?

Desde já eu agradeço sua ajuda veio…
abs…

M

[color=darkblue]Se puder envie o código, mas acredito que não esteja ocorrendo no momento em que você clica no botão fechar uma operação do tipo close(); ou algo semelhante, por isso ele não “conecta novamente” pois não fecha o I/O [/color]

W
package telas;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
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.JOptionPane;

public class CapturaFoto extends javax.swing.JFrame {
    private static final long serialVersionUID = 1L;
    public static Player player = null;
    public CaptureDeviceInfo di = null;  //  @jve:decl-index=0:
    public MediaLocator ml = null;  //  @jve:decl-index=0:
    public JButton capture = null;
    public Buffer buf = null;
    public Image img = null;
    public VideoFormat vf = null;
    public BufferToImage btoi = null;
    public ImagePanel imgpanel = null;
    private JButton captura = null;
    

    public CapturaFoto() {
        super();
        initComponents();
        initialize();
        this.setSize(600,530);
        setLocation(170, 05);
    }
    private void initialize() {
        this.setLayout(new BorderLayout());
        this.setSize(600,500);
        this.add(getCaptura(), BorderLayout.SOUTH);
        this.setVisible(true);
        String str2 = "vfw//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(captura, BorderLayout.SOUTH);
            } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void gravaImg (Image imagem) throws IOException{
        String caminho = "C:/photos"+"00"+".JPG";
   try {
            ImageIO.write((RenderedImage) imagem, "jpg", new File(caminho));
            JOptionPane.showMessageDialog(this, "Imagem Capturada!");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "não foi possivel encontrar " + "o dispositivo para a captura da imagem.");
            e.printStackTrace();
        }
    }
    private JButton getCaptura() {
        if (captura == null) {
            captura = new JButton("Captura");
            captura.setBounds(10, 10, 600, 500);
            captura.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    FrameGrabbingControl fgc = (FrameGrabbingControl) player
                            .getControl("javax.media.control.FrameGrabbingControl");
                    buf = fgc.grabFrame();
                    btoi = new BufferToImage((VideoFormat) buf.getFormat());
                    img = btoi.createImage(buf);
                    try {
                        gravaImg(img);
                    } catch (IOException ex) {
                        Logger.getLogger(CapturaFoto.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
        }
        return captura;
    }

    class ImagePanel extends javax.swing.JPanel {

        private static final long serialVersionUID = 1L;
        public Image myimg = null;

        public ImagePanel() {
            JOptionPane.showMessageDialog(null, "setando a classe");
            setLayout(null);
            setSize(630,530);
        }

        public void setImage(Image img) {
            this.myimg = img;
            repaint();
        }

        @Override
        public void paint(Graphics g) {
            if (myimg != null) {
                g.drawImage(myimg, 0, 0, this);
            }
        }
    }
private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Capturar Foto");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 607, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 489, Short.MAX_VALUE)
        );

        pack();
    }                       
    

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CapturaFoto().setVisible(true);
            }
        });
    }
}
eu acho que vou criar um metodo para finalizar o player ou jogar null na variavel. algo semelhante. valeu veio
W

Já resolvir veio player.close() no metodo que grava imagem e player.stop no metodo de captura a imagem.

Valeu mesmo veio…
Obrigado…

T

ai galera ressucitando o topico, estou com o mesmo problema só que ao iniciar o programa!

o erro :

java.io.IOException: Could not connect to capture device

o codigo da minha aplicação:

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.File;
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 SwingCapture extends Panel implements ActionListener{  
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	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 int cont = 0; 
	
	public SwingCapture(){
		setLayout(new BorderLayout());  
		setSize(100,100);  

		imgpanel = new ImagePanel();  
		capture = new JButton("Capture");  
		capture.addActionListener(this);  
		capture.setLocation(10, 300);
		imgpanel.add(capture);
		capture.setVisible(true);

		String str2 = "vfw//0";  
		di = CaptureDeviceManager.getDevice(str2);  
		ml = new MediaLocator("vfw://0");//di.getLocator();

		try{ 
			
			player = Manager.createRealizedPlayer(ml);  
			player.start();  
			Component comp;  

			if ((comp = player.getVisualComponent()) != null){  
				add(comp,BorderLayout.NORTH);  
			}
			
			add(capture,BorderLayout.SOUTH);  
			add(imgpanel,BorderLayout.NORTH);  
			
		}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(500,550));  
		f.setVisible(true);  
	}  


	public static void playerclose(){  
		player.close();  
		player.stop();
		player.deallocate();  
	}  


	public void actionPerformed(ActionEvent e){
		JComponent c = (JComponent) e.getSource();  
		String caminho = "C:\\Users\\milton\\Desktop\\fotos\\"; //caminho para ser salvo
		if (c == capture){  
			// pegando o frame  
			FrameGrabbingControl fgc = (FrameGrabbingControl)  
			player.getControl("javax.media.control.FrameGrabbingControl");  
			buf = fgc.grabFrame();  

			// Convertendo buffer em imagem  
			btoi = new BufferToImage((VideoFormat)buf.getFormat());  
			img = btoi.createImage(buf);  
			
			// show the image  
			imgpanel.setImage(img);  
			imgpanel.setSize(320, 230);
			
			
			//Verificando se já existe o arquivo com o mesmo nome na pasta!
			File existe = new File(caminho+"test"+cont+".jpg");
			while(existe.exists()){ //se existe incrementa até achar um numero vazio.
				cont++;
				existe = new File(caminho+"test"+cont+".jpg");
			}
			
			// chamando o metodo para salvar a imagem  
			saveJPG(img, caminho+"test"+cont+".jpg");  

		}  
	}  

	class ImagePanel extends Panel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		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");   
		}  

	}
}
M

Dá uma olhada nesse site aqui :

Program multimedia with JMF, Part 2

Criado 14 de julho de 2009
Ultima resposta 24 de jun. de 2011
Respostas 7
Participantes 3