Galera,
preciso fazer um formulário, que contenha um painel, que capture a imagem da webcam…
ja fiz em delphi isso, mas em java, eu não faço idéia…
alguém teria alguma idéia?
Abraços!!!
Galera,
preciso fazer um formulário, que contenha um painel, que capture a imagem da webcam…
ja fiz em delphi isso, mas em java, eu não faço idéia…
alguém teria alguma idéia?
Abraços!!!
Para capturar a imagem tu vais ter que usar alguma biblioteca tipo a JMF.
JMF = Java Media Framework.
Boa Sorte! :thumbup:
Obrigado, vou atrás disso. Abçs!
estou aceitando mais dicas tbm =)
Esse “formulário” é um form de html ou é um form de GUI tipo VB ou JFrame?
Inté.
Fala brother…
então, é pra desktop, esqueci de relatar… JFrame !
:thumbup:
cara, é o seguinte, tou com este mesmo problema só que consegui algumas soluções… tipo consigo capturar a imagem da web cam, consigo salvar e um local especifico do HD… estaria tudo funcionando do geito que eu quero, se não fosse por um pequeno problema… só consigo fazer isso com applet analizei um código da internet e consegui alterar tudo que queria, exceto fazer com que ele fosse executado em um formulario (extenção de um jFrame) quando refaço o programa em uma extenção de jPanel ele não roda… e também não da erro algum… nem erro de compilação nem exception, simplesmente não aparece em lugar algum…
bom eu resolvi metade do problema, quem sabe você não consegue exito daqui pra frente…
segue o codigo abaixo…
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.cdm.CaptureDeviceManager;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
public class WebCamCapture extends Applet implements ActionListener {
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;
public void init() {
JOptionPane.showMessageDialog(null, "inicializou");
this.setLayout(new BorderLayout());
this.setSize(320, 550);
this.setVisible(true);
imgpanel = new ImagePanel();
capture = new JButton("Capture");
capture.addActionListener(this);
// This may differ check the jmf registry for
// correct entry
String str2 = "vfw//0";
di = CaptureDeviceManager.getDevice(str2);
ml = new MediaLocator("vfw://0");
JOptionPane.showMessageDialog(null, "executou di e ml");
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 void paint(Graphics g) {
}
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);
gravaImg(img);
}
}
public void gravaImg (Image imagem){
String caminho = "C:\\Documents and Settings\\Patrick\\Desktop" +
"\\PontoEletronico\\Fotos\\Patrick1.jpg";
try {
ImageIO.write((RenderedImage) imagem, "PNG", new File(caminho));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "não foi possivel encontrar " +
"o dispositivo para a captura da imagem.");
e.printStackTrace();
}
}
class ImagePanel extends Panel {
private static final long serialVersionUID = 1L;
public Image myimg = null;
public ImagePanel() {
JOptionPane.showMessageDialog(null, "setando a classe");
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);
}
}
}
}
ah só mais uma cois se você conseuir… por favor me manda uma mensagem pessoal ok brigadão…
Então, eu tb vou precisar fazer isso, e achei vários links na web.
Um deles é http://forum.java.sun.com/thread.jspa?threadID=247253&messageID=1816659.
Depois que vc fizer rodar, por favor, coloque aqui o código!
cara parece brincadeira... poucas horas depois eu estar enviando esta mensagem informando que já consegui fazer tudo que estava planejando... wow agora até eu me surprenedi.
meu program na verdade é um programa de ponto Eletronico, onde os funcionarios batem o ponto em uma espécie de mainFrame, na empresa... para isso se cadastram e tem sua foto tirada na hora do cadastro e toda vez que vão bater o ponto aparece as informações sobre o funcionario que bateu o ponto... como nome, cargo e também aparece a foto dele... aquela tirada na hora do cadastro...
a parte de cadastro deve ser bem semelhante ao que você está querendo, portanto segue em anexo as duas classes qeu compoe essa rotina de tirar foto durante o cadastro. é válido lembrar que essa rotina tem uma classe Cadastro (que é o cadastro propriamente dito) onde em os campos para digitar as informações, e um painel que vai receber a outra classe, a classe para capturar a imagem. Diferente da Classe de cadastro que é a extenção de um JFrame, essa classe de capturar a imagem é uma extenção de um JPanel.
sem mais delongas.import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class Cadastro {
private JFrame Frame = null; // @jve:decl-index=0:visual-constraint="10,10"
private JLabel labelTit = null;
private JLabel lnome = null;
private JLabel lcargo = null;
private JLabel ldataAdm = null;
private JLabel lsetor = null;
private JLabel lendere = null;
private JLabel lfone = null;
private JLabel lRG = null;
private JTextField fnome = null;
private JTextField fcargo = null;
private JTextField fendere = null;
private JTextField ffone = null;
private JTextField fRG = null;
private JComboBox admDia = null;
private JComboBox admMes = null;
private JComboBox admAno = null;
private JComboBox setor = null;
private JLabel lbConf = null;
private JLabel lbSenha = null;
private JPasswordField conf = null;
private JPasswordField senha = null;
private JButton salvar = null;
private JButton limpar = null;
private JPanel jContentPane = null;
private JButton buttonSair = null;
private JLabel jLabelID = null;
private JTextField jTextFieldID = null;
private JPanel jPanelWebCam = null;
private CapturaFoto capturaFoto1 = null;
public Cadastro() {
inicializa();
}
public void inicializa() {
Frame = new JFrame();
Frame.setLayout(null);
Frame.setSize(844, 582);
Frame.setLocation(100, 100);
Frame.setTitle("Ponto Eletrônico - Cadastro");
Frame.setContentPane(getJContentPane());
Frame.setVisible(true);
}
private Container getJContentPane() {
if (jContentPane == null) {
jLabelID = new JLabel();
jLabelID.setBounds(new Rectangle(523, 59, 167, 27));
jLabelID.setFont(new Font("Dialog", Font.BOLD, 18));
jLabelID.setText("ID do Funcionario");
jContentPane = new JPanel();
jContentPane.setLayout(null);
labelTit = new JLabel();
labelTit.setFont(new Font("Dialog", Font.BOLD, 42));
labelTit.setBounds(170, 8, 537, 35);
labelTit.setText("Cadastro de Funcionários");
lnome = new JLabel("NOME");
lnome.setFont(new Font("Dialog", Font.BOLD, 20));
lnome.setBounds(8, 58, 75, 35);
lcargo = new JLabel("CARGO");
lcargo.setFont(new Font("Dialog", Font.BOLD, 20));
lcargo.setBounds(new Rectangle(11, 200, 73, 26));
ldataAdm = new JLabel("DATA ADMISSÃO");
ldataAdm.setFont(new Font("Dialog", Font.BOLD, 20));
ldataAdm.setBounds(new Rectangle(301, 431, 163, 26));
lsetor = new JLabel("SETOR");
lsetor.setFont(new Font("Dialog", Font.BOLD, 20));
lsetor.setBounds(new Rectangle(13, 298, 69, 26));
lendere = new JLabel("ENDEREÇO");
lendere.setFont(new Font("Dialog", Font.BOLD, 20));
lendere.setBounds(new Rectangle(8, 110, 111, 26));
lfone = new JLabel("TELEFONE");
lfone.setFont(new Font("Dialog", Font.BOLD, 20));
lfone.setBounds(new Rectangle(8, 148, 106, 26));
lRG = new JLabel("CPF");
lRG.setFont(new Font("Dialog", Font.BOLD, 20));
lRG.setBounds(new Rectangle(13, 254, 40, 26));
lbConf = new JLabel("Confirma senha");
lbConf.setBounds(new Rectangle(12, 431, 106, 26));
lbConf.setText("CONFIRMA");
lbConf.setFont(new Font("Dialog", Font.BOLD, 18));
lbSenha = new JLabel("Senha");
lbSenha.setBounds(new Rectangle(11, 388, 77, 26));
lbSenha.setText("SENHA");
lbSenha.setFont(new Font("Dialog", Font.BOLD, 18));
fnome = new JTextField(30);
fnome.setBounds(new Rectangle(133, 66, 334, 26));
fnome.setFont(new Font("Dialog", Font.PLAIN, 18));
fcargo = new JTextField(20);
fcargo.setBounds(new Rectangle(130, 200, 224, 27));
fcargo.setFont(new Font("Dialog", Font.PLAIN, 18));
fendere = new JTextField(30);
fendere.setBounds(new Rectangle(133, 107, 334, 26));
fendere.setFont(new Font("Dialog", Font.PLAIN, 18));
ffone = new JTextField(15);
ffone.setBounds(new Rectangle(132, 151, 169, 26));
ffone.setFont(new Font("Dialog", Font.PLAIN, 18));
fRG = new JTextField(10);
fRG.setBounds(new Rectangle(129, 255, 138, 26));
fRG.setFont(new Font("Dialog", Font.PLAIN, 18));
conf = new JPasswordField(10);
conf.setBounds(new Rectangle(132, 431, 146, 26));
conf.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_ENTER){
if(senha.getText().equals(conf.getText())){
String x = setor.getSelectedItem().toString();
String y = admDia.getSelectedItem()+" "+admMes.getSelectedItem()+" "+admAno.getSelectedItem();
String z = "patrick.gif";
Banco.insereCad(fnome.getText(), fendere.getText(), ffone.getText(), fcargo.getText(), fRG.getText(), x, y, senha.getText(),z);
fnome.setText("");
fendere.setText("");
ffone.setText("");
fcargo.setText("");
fRG.setText("");
conf.setText("");
senha.setText("");
jTextFieldID.setText("00"+(Integer.parseInt(Banco.retornaGeral("select max(ID) from Funcionarios").toString())+1));
}else{
JOptionPane.showMessageDialog(null, "A senha não confere");
}
}
}
});
senha = new JPasswordField(10);
senha.setBounds(new Rectangle(132, 392, 142, 26));
admDia = new JComboBox();
admDia.setBounds(new Rectangle(476, 432, 71, 25));
admMes = new JComboBox();
admMes.setBounds(new Rectangle(562, 432, 119, 25));
admAno = new JComboBox();
admAno.setBounds(new Rectangle(691, 432, 60, 25));
setor = new JComboBox();
setor.setBounds(new Rectangle(128, 298, 141, 25));
insereBox();
jContentPane.add(labelTit);
jContentPane.add(lnome, lnome.getName());
jContentPane.add(fnome);
jContentPane.add(lcargo);
jContentPane.add(fcargo);
jContentPane.add(ldataAdm);
jContentPane.add(admDia);
jContentPane.add(admMes);
jContentPane.add(admAno);
jContentPane.add(lsetor);
jContentPane.add(setor);
jContentPane.add(lendere);
jContentPane.add(fendere);
jContentPane.add(lfone);
jContentPane.add(ffone);
jContentPane.add(lRG);
jContentPane.add(fRG);
jContentPane.add(lbConf);
jContentPane.add(conf);
jContentPane.add(lbSenha);
jContentPane.add(senha);
jContentPane.add(getSalvar(), null);
jContentPane.add(getLimpar(), null);
jContentPane.add(getButtonSair(), null);
jContentPane.add(jLabelID, null);
jContentPane.add(getJTextFieldID(), null);
jContentPane.add(getJPanelWebCam(), null);
}
return jContentPane;
}
private void insereBox() {
for (int x = 1; x <= 31; x++) {
admDia.addItem(x);
}
for (int x = 1980; x <= 2020; x++) {
admAno.addItem(x);
}
// preencher a caixa de mes
admMes.addItem("Janeiro");
admMes.addItem("Fevereiro");
admMes.addItem("Março");
admMes.addItem("Maio");
admMes.addItem("Junho");
admMes.addItem("Julio");
admMes.addItem("Agosto");
admMes.addItem("Setembro");
admMes.addItem("Outubro");
admMes.addItem("Novembro");
admMes.addItem("Dezembro");
// prenecher Setor
setor.addItem("Ti");
setor.addItem("RH");
setor.addItem("Vendas");
setor.addItem("Portaria");
setor.addItem("Secretaria");
setor.addItem("Coordenação");
setor.addItem("Administração");
setor.addItem("Cobrança");
}
/**
* This method initializes buttonSair
*
* @return javax.swing.JButton
*/
private JButton getButtonSair() {
if (buttonSair == null) {
buttonSair = new JButton();
buttonSair.setBounds(new Rectangle(509, 501, 80, 26));
buttonSair.setText("Sair");
buttonSair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
Frame.setVisible(false);
Frame.setDefaultCloseOperation(0);
}
});
}
return buttonSair;
}
private JButton getLimpar(){
if (limpar == null) {
limpar = new JButton("Limpar");
limpar.setBounds(new Rectangle(271, 501, 74, 26));
limpar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
fnome.setText("");
fendere.setText("");
ffone.setText("");
fcargo.setText("");
fRG.setText("");
conf.setText("");
senha.setText("");
}
});
}
return limpar;
}
private JButton getSalvar(){
if(salvar == null){
salvar = new JButton("Salvar");
salvar.setBounds(new Rectangle(390, 502, 74, 26));
salvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(senha.getText().equals(conf.getText())){
String x = setor.getSelectedItem().toString();
String y = admDia.getSelectedItem()+" "+admMes.getSelectedItem()+" "+admAno.getSelectedItem();
String z = "patrick.gif";
Banco.insereCad(fnome.getText(), fendere.getText(), ffone.getText(), fcargo.getText(), fRG.getText(), x, y, senha.getText(),z);
fnome.setText("");
fendere.setText("");
ffone.setText("");
fcargo.setText("");
fRG.setText("");
conf.setText("");
senha.setText("");
jTextFieldID.setText("00"+(Integer.parseInt(Banco.retornaGeral("select max(ID) from Funcionarios").toString())+1));
}else{
JOptionPane.showMessageDialog(null, "A senha não confere");
}
}});
}
return salvar;
}
/**
* This method initializes jTextFieldID
*
* @return javax.swing.JTextField
*/
private JTextField getJTextFieldID() {
if (jTextFieldID == null) {
jTextFieldID = new JTextField();
jTextFieldID.setBounds(new Rectangle(700, 57, 59, 30));
jTextFieldID.setEditable(false);
jTextFieldID.setFont(new Font("Dialog", Font.BOLD, 18));
jTextFieldID.setText("00"+(Integer.parseInt(Banco.retornaGeral("select max(ID) from Funcionarios").toString())+1));
}
return jTextFieldID;
}
/**
* This method initializes jPanelWebCam
*
* @return javax.swing.JPanel
*/
private JPanel getJPanelWebCam() {
if (jPanelWebCam == null) {
jPanelWebCam = new JPanel();
jPanelWebCam.setLayout(null);
jPanelWebCam.setBounds(new Rectangle(477, 103, 347, 288));
jPanelWebCam.setBorder(BorderFactory.createTitledBorder(null,
"Foto", TitledBorder.LEADING, TitledBorder.TOP,
new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51)));
jPanelWebCam.add(getCapturaFoto1(), null);
}
return jPanelWebCam;
}
private CapturaFoto getCapturaFoto1() {
if (capturaFoto1 == null) {
capturaFoto1 = new CapturaFoto();
capturaFoto1.setBounds(new Rectangle(10, 22, 327, 259));
}
return capturaFoto1;
}
}
é valeu a pena ter passado a noite em claro para tentar fazer isso funcionar...
segue em anexo a classe extenção de JPanel para a captura da foto...
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.cdm.CaptureDeviceManager;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class CapturaFoto extends JPanel {
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 static final long serialVersionUID = 1L;
private JButton captura = null;
public CapturaFoto() {
super();
initialize();
}
private void initialize() {
this.setLayout(new BorderLayout());
this.setSize(327, 259);
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){
String caminho = "C:\\Documents and Settings\\Patrick\\Desktop" +
"\\PontoEletronico\\Fotos\\"+"00"+(Integer.parseInt(Banco.
retornaGeral("select max(ID) from Funcionarios").toString())+1)+".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(50, 50, 50, 50);
captura.addActionListener(new java.awt.event.ActionListener() {
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);
gravaImg(img);
}
});
}
return captura;
}
class ImagePanel extends Panel {
private static final long serialVersionUID = 1L;
public Image myimg = null;
public ImagePanel() {
JOptionPane.showMessageDialog(null, "setando a classe");
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);
}
}
}
}
Desculpe reavivar esse topico, mas é que eu preciso saber como faz para salavar a imagem em outro tamanho que não seja 320 x 240.
Desculpe reavivar esse topico, mas é que eu preciso saber como faz para salavar a imagem em outro tamanho que não seja 320 x 240.Fera, estou também na luta com captura de vídeo pela webcam e consegui algum progresso... Fiz pequenas modificações numa classe que encontrei e estou incorporando métodos dela à minha aplicação; já serve para alguma coisa... OBS.: Lista todos os formatos (dimensões) de imagem que a webcam detectada suportar (320x140, 640x480, etc)... Espero que lhe seja útil...
package doctorpack;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.media.*;
import javax.media.protocol.*;
import javax.media.format.*;
import javax.media.control.*;
import javax.media.datasink.*;
/*
*
* Lindoélio Lázaro
*
*/
public class CapturaImagens extends JFrame {
private JButton captureButton;
private Component progressoGravacao;
private Format formats[], formatoSelecionado;
private FormatControl controlesFormato[];
private CaptureDeviceInfo informacoesDispositivo;
private Vector dispositivosLista;
private DataSource inSource, saida;
private DataSink dataSink;
private Processor processor;
public CapturaImagens() {
super( "Captura..." );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel );
captureButton = new JButton( "Capturar e Salvar" );
buttonPanel.add( captureButton, BorderLayout.CENTER );
captureButton.addActionListener( new CaptureHandler() );
Manager.setHint( Manager.LIGHTWEIGHT_RENDERER, Boolean.TRUE );
addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent windowEvent ) {
if ( processor != null )
processor.close();
}
}
);
}
private class CaptureHandler implements ActionListener {
public void actionPerformed( ActionEvent actionEvent ) {
dispositivosLista = CaptureDeviceManager.getDeviceList( null );
if ((dispositivosLista == null) || (dispositivosLista.size() == 0)) {
informarErro( "Nenhum dispositivo de captura encontrado!" );
return;
}
// lista todos os dispositivos encontrados
String nomesDispositivos[] = new String[dispositivosLista.size()];
for ( int i = 0; i < dispositivosLista.size(); i++){
informacoesDispositivo = (CaptureDeviceInfo)dispositivosLista.elementAt(i);
nomesDispositivos[i] = informacoesDispositivo.getName();
}
int indiceDispositivoSelecionado = capturarIndiceDispositivoSelecionado(nomesDispositivos);
if (indiceDispositivoSelecionado == -1)
return;
// pega informações do dispositivo selecionado
informacoesDispositivo = (CaptureDeviceInfo)dispositivosLista.elementAt(indiceDispositivoSelecionado);
formats = informacoesDispositivo.getFormats();
if (inSource != null)
inSource.disconnect();
try {
inSource = Manager.createDataSource(informacoesDispositivo.getLocator());
controlesFormato = ((CaptureDevice)inSource).getFormatControls();
formatoSelecionado = capturarFormatoSelecionado(formats);
if (formatoSelecionado == null)
return;
mostrarFormatoDispositivo(formatoSelecionado);
captureSaveFile();
}
catch (NoDataSourceException noData) {
noData.printStackTrace();
}
catch (IOException io) {
io.printStackTrace();
}
}
}
public void mostrarFormatoDispositivo(Format formatoAtual) {
for (int i = 0; i < controlesFormato.length; i++) {
if (controlesFormato[i].isEnabled() ) {
controlesFormato[i].setFormat(formatoAtual);
System.out.println ("Formato atualmente como "+controlesFormato[i].getFormat() );
}
}
}
public int capturarIndiceDispositivoSelecionado(String[] names) {
String name = (String) JOptionPane.showInputDialog(this, "Selecione um dispositivo: ", "Dispositivo",
JOptionPane.QUESTION_MESSAGE,
null,
names,
names[0]);
if (name != null)
return Arrays.binarySearch(names, name);
else
return -1;
}
public Format capturarFormatoSelecionado(Format[] formatosLista) {
return (Format) JOptionPane.showInputDialog(this,"Selecione um formato: ", "Formatos suportados",
JOptionPane.QUESTION_MESSAGE,
null,
formatosLista,
null);
}
public void informarErro(String error) {
JOptionPane.showMessageDialog(this, error, "Informação", JOptionPane.ERROR_MESSAGE);
}
public File capturarArquivoSalvo() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int resultado = fileChooser.showSaveDialog(this);
if (resultado == JFileChooser.CANCEL_OPTION)
return null;
else
return fileChooser.getSelectedFile();
}
public void showSaveMonitor() {
int result = JOptionPane.showConfirmDialog(this,progressoGravacao, "Capturando...",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE);
if ((result == JOptionPane.OK_OPTION) || (result == JOptionPane.CLOSED_OPTION)) {
processor.stop();
processor.close();
JOptionPane.showMessageDialog(this,"Captura salva com sucesso!");
}
}
public void captureSaveFile() {
Format outFormats[] = new Format[1];
outFormats[0] = formatoSelecionado;
FileTypeDescriptor outFileType = new FileTypeDescriptor(FileTypeDescriptor.MSVIDEO);
try {
processor = Manager.createRealizedProcessor(new ProcessorModel(inSource, outFormats, outFileType));
if (!gravarDados())
return;
processor.start();
MonitorControl controles = (MonitorControl)processor.getControl("javax.media.control.MonitorControl");
progressoGravacao = controles.getControlComponent();
showSaveMonitor();
}
catch (NoProcessorException noProcessor) {
noProcessor.printStackTrace();
}
catch (CannotRealizeException cannotRealize) {
cannotRealize.printStackTrace();
}
catch (IOException ioException) {
ioException.printStackTrace();
}
}
public boolean gravarDados() {
File arquivoSalvo = capturarArquivoSalvo();
if (arquivoSalvo == null)
return false;
saida = processor.getDataOutput();
if (saida == null) {
informarErro("Sem saída para processar!");
return false;
}
try {
MediaLocator localizacaoArquivo = new MediaLocator(arquivoSalvo.toURL());
dataSink = Manager.createDataSink(saida, localizacaoArquivo);
dataSink.addDataSinkListener(new DataSinkListener() {
public void dataSinkUpdate(DataSinkEvent dataEvent) {
if (dataEvent instanceof EndOfStreamEvent)
dataSink.close();
}
}
);
dataSink.open();
dataSink.start();
}
catch ( NoDataSinkException noDataSinkException ) {
noDataSinkException.printStackTrace();
return false;
}
catch ( SecurityException securityException ) {
securityException.printStackTrace();
return false;
}
catch ( IOException ioException ) {
ioException.printStackTrace();
return false;
}
return true;
}
}
Mano estou me matando com umna aplicação, ela também deverá capturar imagem de uma WebCam mas nas linha onde está os “Erro aqui” eu não consigo encontrar algum device:
public Camera() {
setLayout(new BorderLayout());
setSize(320,550);
ImgPanel = new ImagePanel();
BuCapture = new JButton("Capturar");
BuCapture.addActionListener(this);
String str1 = "vfw:Logitech USB Video Camera:0";
String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
CaptureDeviceInfo = (CaptureDeviceInfo) CaptureDeviceManager.getDevice(str1); //Erro aqui
MediaLocator = CaptureDeviceInfo.getLocator(); //Erro aqui
try {
Player = Manager.createRealizedPlayer(MediaLocator);
Player.start();
Component Componente;
if ((Componente = Player.getVisualComponent()) != null) {
add(Componente,BorderLayout.NORTH);
}
add(BuCapture,BorderLayout.CENTER);
add(ImgPanel,BorderLayout.SOUTH);
} catch (Exception err) {
err.printStackTrace();
Que tipo de camera vocês estam usando?
Outra observação:
Para teste, eu compilei seus fontes e aconteceu a mesma coisa ele não demonstra a camera, por favor me ajudem?
Bom dia, fera…
Poste o erro que está dando…
Linkel … sou novato em Java … como eu faria para testar essa sua classe … poderia por favor me exemplificar ???
fiz alguns testes mas não tive sucesso …
já instalei e testei o JMF e está funcionando perfeitamente junto com a minha webcam …
obrigado
Leonardo
Mano estou me matando com uma aplicação, ela também deverá capturar imagem de uma WebCam mas nas linha onde está os “Erro aqui” eu não consigo encontrar algum device…
String str1 = "vfw:Logitech USB Video Camera:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
Que tipo de camera vocês estam usando?
Para teste, eu compilei seus fontes e aconteceu a mesma coisa ele não demonstra a camera, por favor me ajudem?
Linkel … sou novato em Java … como eu faria para testar essa sua classe … poderia por favor me exemplificar ???
fiz alguns testes mas não tive sucesso …
já instalei e testei o JMF e está funcionando perfeitamente junto com a minha webcam…
“Sun streaking cold, and an old man wondering lonely…”
Jethro Tull - Aqualung (versiculo 15).
Ai tá o que tu quer…
http://java.sun.com/developer/technicalArticles/Programming/robotics/index.html
Eu estou usando uma aplicação que captura imagem so que eu não estou consegindo e dimensionar para uma imagem 3x4, o que eu devo fazer?
Olá galera, estou tentando fazer uma applet para captura de foto da webcam com jsf
vi o código acima da applet mas não consegui exibir o JButton
ele aparece a imagem da webcam mas não aparece nada para clicar e tirar a foto.
alguem pode me ajudar?
Valeu.
Amigos por favor me ajudem, peguei vários exemplos e nada, o mais certinho até agora foi o código acima da applet
preciso de uma applet que apareça a imagem da webcam e um botão para capturar a imagem, salvando a imagem em jpeg.
por favor me ajudem!!!
Pow veio naum sei se isso pode te ajudar eu estou uzando swing mas pode extends applet
blic class Fotografia 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;
private ClienteDB cliDB = null;
private String pathFotos = "";
public int clienteID = 0;
/** Creates new form Foto */
public Fotografia(ClienteDB DB, int cliID, String path) {
super();
this.cliDB = DB;
this.clienteID = cliID;
this.pathFotos = path;
initComponents();
initialize();
//setLocation(170, 05);
setLocation(300, 300);
getContentPane().add(captura);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
if (player != null) {
player.close();
}
player.deallocate();
}
});
}
private void initialize() {
this.setLayout(new BorderLayout());
// this.setSize(300, 290);
this.setSize(300, 300);
this.setMaximumSize(new Dimension(largura, altura));
this.setMinimumSize(new Dimension(largura, altura));
this.add(getCaptura(), BorderLayout.SOUTH);
this.setVisible(true);
//String str2 = "vfw://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(captura, BorderLayout.SOUTH);
} catch (Exception e) {
e.printStackTrace();
}
}
private JButton getCaptura() {
if (captura == null) {
captura = new JButton(" -- Capturar imagem -- ");
captura.setBounds(new Rectangle(10, 10, 10, 10)); //Corresponde a posição(x=50 e y=50) e Largura(width=50) e Altura(height=50)
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();
player.stop();
player.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
return captura;
}
//public void gravaImg(Image imagem) throws IOException {
public void gravaImg() throws IOException {
String caminho = "";
String nmArquivo = String.valueOf(clienteID) + ".jpg";
try {
caminho += this.pathFotos + nmArquivo;
ImageIO.write((RenderedImage) img, "jpg", new File(caminho));
JOptionPane.showMessageDialog(this, "Informações e imagem registradas com sucesso.");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Não foi possível localizar o dispositivo para a captura da imagem.");
e.printStackTrace();
}
try {
img = new ImageIcon(caminho).getImage();
} catch (RuntimeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ImageUtils.saveCompressedImage(ImageUtils.resizeImage(img, ImageUtils.IMAGE_JPEG, 100, 300), caminho, ImageUtils.IMAGE_JPEG);
int teste = ImageUtils.IMAGE_JPEG;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.close();
this.dispose();
}
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(largura, altura);
setMinimumSize(new Dimension(largura, altura));
setMaximumSize(new Dimension(largura, altura));
}
public void setImage(Image img) {
this.myimg = img;
repaint();
}
@Override
public void paint(Graphics g) {
if (myimg != null) {
g.drawImage(myimg, 0, 0, this);
}
}
}
public int retornarFotoID() {
return clienteID;
}
Pessoal, não to conseguindo colocar pra rodar o código acima.
Dá os seguintes erros:
Exception in thread “main” java.lang.Error: Unresolved compilation problems:
Access restriction: The type CaptureDeviceInfo is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type Manager is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type MediaLocator is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type Player is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type CaptureDeviceManager is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type FrameGrabbingControl is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type VideoFormat is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type BufferToImage is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type Player is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type CaptureDeviceInfo is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type MediaLocator is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type Buffer is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type VideoFormat is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type BufferToImage is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type CaptureDeviceManager is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The method getDevice(String) from the type CaptureDeviceManager is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The constructor MediaLocator(String) is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type MediaLocator is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type Manager is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The method createRealizedPlayer(MediaLocator) from the type Manager is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The method start() from the type Player is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The method getVisualComponent() from the type Player is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type FrameGrabbingControl is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type FrameGrabbingControl is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The method getControl(String) from the type Controller is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The method grabFrame() from the type FrameGrabbingControl is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The constructor BufferToImage(VideoFormat) is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type BufferToImage is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The type VideoFormat is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The method getFormat() from the type Buffer is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
Access restriction: The method createImage(Buffer) from the type BufferToImage is not accessible due to restriction on required library D:\Arquivos de programas\Java\jre6\lib\ext\jmf.jar
at CapturaFoto.<init>(CapturaFoto.java:12)
at Foto.getCapturaFoto1(Foto.java:61)
at Foto.<init>(Foto.java:44)
at Foto.main(Foto.java:70)
Utilizar jmf não é uma opção adequada. Jmf foi descontinuada a zilhões de anos atras. A única opção é fazer jni com directshow.
http://www.humatic.de/htools/dsj.htm
Ola boa terde pessoal.
Então com base no post eu criei uma outro form só para a captura da imagem mais quando eu gero o jar o mesmo não executa, alguém pode dar uma luz de como eu faço para gerar o jar.Para que eu possa ter uma noção de onde estou errando.Valeu…
Eu preciso fazer em vez de gravar uma imagem, gravar um vídeo. Alguém ja conseguiu fazer isso?
Utiliza a JMF.jar do diretório do JMF instalado.
Isto resolveu o meu problema.
amigos estou tentando fazer essa captura d imagem agora, mas coloquei o codigo mas ele nao reconhe o medialocator e nem CaptureDeviceInfo,e nem Manager.createDataSource podem me ajudar?
valeu
ola jrfercar pode me ajudar com o JMF…estou aprendendo a capturar imagem agora…
valeu
Cara está dando um erro de compilação que diz que a Classe Banco não existe, que classe é essa?
amigos
estou precisando desenvolver esta aplicação
um cadastro de acesso com foto
preciso dar um import em algum .jar ?
Psvtec
voce configurou a maquina ou o pc pra quando tirar a foto salvar na pasta
como configurou ?
e o nome do arquivo ?
String caminho = "C:\\Documents and Settings\\Patrick\\Desktop" +
"\\PontoEletronico\\Fotos\\"+"00"+(Integer.parseInt(Banco.
retornaGeral("select max(ID) from Funcionarios").toString())+1)+".JPG";
funciona apenas com webcam ?
e camera digital ?
olá pessoal
consegui montar um cadastro com foto
mas a questão, o cara clica na web cam pra tirar a foto, dae tem que salvar em um local
e no java chamar essa figura que ele salvou
tem como ser + automatico isso :?
obrigado
Psvtec sera que vc pode me ajudar, estou tentando executar essa classe porem nao entendo porque ele da esse erro!
javax.media.NoPlayerException: Cannot find a Player for :vfw://0
at javax.media.Manager.createPlayerForContent(Manager.java:1412)
at javax.media.Manager.createPlayer(Manager.java:417)
at javax.media.Manager.createRealizedPlayer(Manager.java:553)
at packageWebCapture.CapturaFoto.initialize(CapturaFoto.java:61)
at packageWebCapture.CapturaFoto.(CapturaFoto.java:46)
at packageWebCapture.TesteCap.main(TesteCap.java:11)
Boa tarde, pessoal alguem poderia me ajudar com o seguinte problema,
Estou utilizando JMF para capturar imagens, mas gostaria de saber se tem como selecionar a câmera antes de começar a Captura,
pois quando inicializo o sistema ele pega a câmera padrão do notebook.
Gostaria de por exemplo, ter 3 câmeras conectadas mas quando eu iniciar a aplicação escolher qual irei utilizar…
Segue abaixo o código que inicializa a WebCam
public boolean ligaDesligaWebCam() throws
IOException, NoPlayerException, CannotRealizeException {
if (status == true) {
JOptionPane.showMessageDialog(null, "A camera já está ligada");
} else if(status == false) {
player = Manager.createRealizedPlayer(new MediaLocator("vfw://0"));
//player.getControlPanelComponent().setSize(300, 280);
player.getVisualComponent().setSize(300, 280);
player.start();
jPanelWebCamVideo.add(player.getVisualComponent());
status = true;
}
return status;
}