I'm trying to write an image to the MySql database, the table is just below, the code to load the image is right after that, I'm using a button to load a JLabel, after that I use another button to insert the image image in the database, just below the insert code, I can not write to the database.
Mysql Bank
create table imagens(
id int not null auto_increment,
cpf varchar(15) not null,
foto blob null,
primary key (id),
foreign key (cpf)
references funcionario(cpf)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
Here and where I load the image in JLabel from a JFileChooser
JFileChooser fileChooser = new JFileChooser(); //Cria o objeto do tipo Janela JFileChooser
fileChooser.setDialogTitle("Escolha a Foto"); //Define o título do JFileChooser
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); //Define que só serão abertos arquivos
{
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
File arquivo = fileChooser.getSelectedFile();//arquivo
BufferedImage bi = ImageIO.read(arquivo); //carrega a imagem real num buffer
BufferedImage aux = new BufferedImage(100, 80, bi.getType());//cria um buffer auxiliar com o tamanho desejado
Graphics2D g = aux.createGraphics();//pega a classe graphics do aux para edicao
AffineTransform at = AffineTransform.getScaleInstance((double) 100 / bi.getWidth(), (double) 80 / bi.getHeight());//cria a transformacao
g.drawRenderedImage(bi, at);//pinta e transforma a imagem real no auxiliar
foto.setIcon(new ImageIcon(aux));//seta no jlabel
foto.setText(null);
// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//Jogue a imagem lá dentro do byteArrayOutputStream
//ImageIO.write(aux, "png", byteArrayOutputStream);
}catch (IOException ex) {
}
}
}
This is my insert.
String prep = "INSERT INTO imagens (foto,cpf) VALUES(?,?)";
Image image = ((ImageIcon)foto.getIcon()).getImage();
PreparedStatement sttmt = con.prepareStatement(prep);
JTextField cpff = cpf;
sttmt.setBytes(1, bytes(image));
sttmt.setString(2, cpf.getText());
sttmt.execute();
sttmt.close();