Saludos a Todos .. hace mucho que no entraba ;D
Estoy haciendo una Aplicacion de escritorio y consiste en :
en mi formulario tengo conectada una webcam (quiero hacer un control de entradas)
y cada vez que ingrese un usuario se logee y aparezca su foto y tambien que tome una instantanea con la webcam ..
Mi problema es que obtengo la imagen desde la webcam ... pero no e podido guardarla en el SQL ... me quedo asta aqui
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write((RenderedImage) img, "JPEG", out);
InputStream in = new ByteArrayInputStream(out.toByteArray());
String cad_sql = "{call Tsp_graba_control(?,?,?) }" ;
da.setInt(1, 1);
da.setString(2, "IN");
// eh Aqui mi problema al enviar la imagen
da.setByte(3,in);
int rpt = da.executeUpdate();
Me compila y no manda error ... pero no graba ... o de esta forma no se guarda la imagen ... en .NET lo que hacia era pasarlo a bytes pero en java no se !!
:-(
tenes que hacer lo mismo que en .NET, los metodos son iguales hasta para VB6 incluso es lo mismo, pasas la imagen a bytes y guardas eso en la base de datos, para recuperar al reves recuperas los byes y los convertis a imagen.
para SQLite usa campo tipo BLOB , para MySQL tambien, para SQL Server podes usar el campo tipo image (pero esta en desuso) o sino varbinary(max).
saludos.
Gracias Doc .. pero la duda que tengo es que en mi caso no obtengo una imagen desde la computadora . . que seria con un dialogo como JFileChooser ..
Yo obtengo mi Imagen desde una webcam ,,
La imagen la tengo en dato Image ;
Image img=null;
FrameGrabbingControl fgc = (FrameGrabbingControl)
//Player es la variable de JMF
player.getControl("javax.media.control.FrameGrabbingControl");
Buffer buf = fgc.grabFrame();
// creamos la imagen awt
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
bueno mi dida seria como convertir la variable img (Image) a Byte[] para poder guardarlo en la BD ... estado buscando y la mayoria de ejemplos de internet estan con imagenes que optienen de la pc .. no de el componente player
te entiendo, yo programo en java pero para Android, o sea los controles son totalmente diferente a los de windows, pero este codigo lo saque de internet, te puede ayudar.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Acceder2Frames.java
*
* Created on 30/06/2010, 10:15:01 PM
*/
package com.blogspot.rolandopalermo.sockets;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
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.Processor;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.Timer;
/**
*
* @author Rolando
*/
public class Acceder2Frames extends javax.swing.JFrame {
//Atributos necesarios para acceder a una cámara web
private static Player player = null;
private MediaLocator localizador = null;
private Processor p;
private CaptureDeviceInfo dispositivo = null;
private static String source = "vfw:Microsoft WDM Image Capture (Win32):0";
private Timer timer;
private Buffer buffer;
private BufferToImage buffer_image = null;
/** Creates new form Acceder2Frames */
public Acceder2Frames(String host) {
initComponents();
servidorChat = host;
dispositivo = CaptureDeviceManager.getDevice(source);
localizador = dispositivo.getLocator();
timer = new Timer (1, new ActionListener () { //Cada 1 milisegundo capturará el frame de video
public void actionPerformed(ActionEvent e) {
FrameGrabbingControl fgc = (FrameGrabbingControl)player.getControl("javax.media.control.FrameGrabbingControl");
buffer = fgc.grabFrame();
// Convert it to an image
buffer_image = new BufferToImage((VideoFormat)buffer.getFormat());
BufferedImage bufferedImage = (BufferedImage)buffer_image.createImage(buffer);
ByteArrayOutputStream salidaImagen = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "jpg", salidaImagen);
byte[] bytesImagen = salidaImagen.toByteArray();
salida.writeObject( bytesImagen );
salida.flush();
// panelCaptura.setImage(img);
} catch ( Exception excepcionEOF ) {
System.err.println( "El cliente termino la conexión" );
}
}
});
setLocationRelativeTo(null);
setVisible(true);
}
private void iniciarCaptura() {
try {
player = Manager.createRealizedPlayer(localizador);
player.start();
if (player.getVisualComponent() != null) {
panelVideo.add(player.getVisualComponent(), BorderLayout.CENTER);
panelVideo.updateUI();
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
public void acceso2Frames() {
timer.start();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
panelVideo = new javax.swing.JPanel();
panelOpciones = new javax.swing.JPanel();
botonSalir = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Captura de Video - Transmisor de video");
panelVideo.setLayout(new java.awt.BorderLayout());
panelOpciones.setBackground(new java.awt.Color(204, 204, 204));
botonSalir.setText("Cerrar");
botonSalir.setOpaque(false);
botonSalir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonSalirActionPerformed(evt);
}
});
panelOpciones.add(botonSalir);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(panelVideo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
.addComponent(panelOpciones, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelVideo, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panelOpciones, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void botonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonSalirActionPerformed
// TODO add your handling code here:
if(player != null) {
player.close();
player.deallocate();
}
timer.stop();
cerrarConexion();
System.exit(0);
}//GEN-LAST:event_botonSalirActionPerformed
private void ejecutarCliente() {
try {
conectarAServidor(); // Paso 1: crear un socket para realizar la conexión
salida = new ObjectOutputStream( cliente.getOutputStream() );
salida.flush(); // vacÃar búfer de salida para enviar información de encabezado
acceso2Frames();
} catch ( EOFException excepcionEOF ) {
System.err.println( "El cliente termino la conexión" );
} catch ( IOException excepcionES ) {
excepcionES.printStackTrace();
}
} // fin del método ejecutarCliente
// conectarse al servidor
private void conectarAServidor() throws IOException {
cliente = new Socket( InetAddress.getByName( servidorChat ), 12345 );
}
private void cerrarConexion() {
System.out.println( "\nCerrando conexión" );
try {
salida.close();
cliente.close();
} catch( IOException excepcionES ) {
excepcionES.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
setDefaultLookAndFeelDecorated(true);
Acceder2Frames ventana = new Acceder2Frames("127.0.0.1");
ventana.iniciarCaptura();
ventana.ejecutarCliente();
}
private ObjectOutputStream salida;
private String servidorChat;
private Socket cliente;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton botonSalir;
private javax.swing.JPanel panelOpciones;
private javax.swing.JPanel panelVideo;
// End of variables declaration//GEN-END:variables
}
fijate ahi tenes como lo convierte a Bytes, al principio del codigo cuando usa "javax.media.control.FrameGrabbingControl" pero no usa el Image comun usa otro objeto.
saludos.
exacto .... hasta aqui logre convertir a bytes[] solo que al mandarlo a la bd el campo FOTO(img) me dice :
"comilla no cerrada despues de #?.A% " algo azi .. azi que lo envie como cadena .lo guardo pero al verificar si estaban las img no eran ... salian todo plomas ,,
por lo pronto y la urgencia que tengo , lo e echo a la fuerza .guardando la img a la pc una carpeta temporal.y de hay la convierto a byte para pasarla a la BD ,,, y asi si logre guardarlo.... pero aun me quedo con la duda pero ya la encontrare en el camino ... Gracias Amigo seba123neo
puedes pasarla a bytes de la siguiente forma:
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2d = bufferedImage.createGraphics();
graphics2d.drawImage(image, 0, 0, null);
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
byte bytes[]=byteArrayOutputStream.toByteArray();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}