I am fetching a image from database and directly read it into panel using Imageio.read method with Bufferimage reference variable but it gives me error javax.imageio.IIOException: Can't read input file! I don't understand why it gives me error.
My database code:
public class ValidateClass {
public static byte[] validateImageAndEmpId(Connection con, String empId) {
byte[] imagedata = null;
try {
PreparedStatement ps = con.prepareStatement("select image from fingerprint where empId=?");
ps.setString(1, empId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("image");
imagedata = blob.getBytes(1, (int) blob.length());
System.out.println("Length" + imagedata);
System.out.println("testlen" + imagedata.length);
}
} catch (Exception e) {
e.printStackTrace();
}
return imagedata;
}
}
Code where I call this method:
public CEntityForm() {
jButtonStep1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButtonStep3_actionPerformed(e);
}
});
/*jButtonStep1 for 1 to 1 match fingerprint matching which is not in use */
jtool.add(jButtonStep1);
try {
// Taking picture1
//Set picture new
m_bimage1 = ImageIO.read(new File(new java.io.File("").getAbsolutePath() + "\\L1Right.Jpeg"));
m_panel1.setBufferedImage(m_bimage1);
//Send image for skeletinization
m_finger1.setFingerPrintImage(m_bimage1);
finger1 = m_finger1.getFingerPrintTemplate();
//See what skeletinized image looks like
m_bimage1 = m_finger1.getFingerPrintImageDetail();
m_panel1.setBufferedImage(m_bimage1);
//fingerprint matching details of finger 1 in number format so commented jtextfield2
// jTextField1.setText(m_finger1.ConvertFingerPrintTemplateDoubleToString(finger1));
/*end of picture 1 details*/
// Taking picture2
//Set picture new
Connection con = Conn.getConnection();
byte[] bytearry = ValidateClass.validateImageAndEmpId(con, $emp_Id);
// System.out.println("Input="+input);
m_bimage2 = ImageIO.read(new ByteArrayInputStream(bytearry));
// m_bimage2 = ImageIO.read(new File(new java.io.File("").getAbsolutePath() + "\\L1Right_Copy.Jpeg"));
m_panel2.setBufferedImage(m_bimage2);
//Send image for skeletinization
m_finger2.setFingerPrintImage(m_bimage2);
finger2 = m_finger2.getFingerPrintTemplate();
//See what skeletinized image looks like
m_bimage2 = m_finger2.getFingerPrintImageDetail();
m_panel2.setBufferedImage(m_bimage2);
//fingerprint matching details of finger 2 in number format so commented jtextfield2
//jTextField2.setText(m_finger2.ConvertFingerPrintTemplateDoubleToString(finger2));
/*end of picture 1 details*/
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.PLAIN_MESSAGE);
}
this.getContentPane().setLayout(new GridLayout(2, 2));
this.getContentPane().add(m_panel1);
this.getContentPane().add(m_panel2);
this.getContentPane().add(jtool);
this.setTitle("Entity");
this.setSize(new Dimension(800, 700));
}
Main Method
public class Testmain {
public static void main(String[] args) {
try{
new CEntityForm().setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
Output:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at main.CEntityForm.<init>(CEntityForm.java:81)
at main.Testmain.main(Testmain.java:18)
The exception seems to come from your other call to ImageIO.read(); the first one in the constructor. There you're passing a file that presumably doesn't exist.
Related
I have managed to display the first image but it does not display the next blob image in the column
PS. i have double checked everything in the DB even used the query in a Workbench THE query in the code is correct!, it returns exactly what i wanted
Thank you in advance.
My code:
public BufferedImage image()
{
System.out.println("I am in Image");
try {
System.out.println("trying to find com.mysql.jdbc.driver");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Success");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select image from images where state = 0 ");
while (rs.next())
{
java.sql.Blob blob = rs.getBlob(1);
System.out.println(blob);
System.out.println(blob.length());
InputStream in = blob.getBinaryStream(1,blob.length());
System.out.println(!rs.next());
System.out.println(in);
BufferedImage image = ImageIO.read(in);
System.out.println(image);
// Display the image
ImageIcon icon = new ImageIcon(image);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(500,800);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return image;
}
con.close();
System.out.println("reached here");
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
the Problem was that for some reason it was skipping one row after changing if(!rs.next) to
if (rs.next())
{
anyResults = true;
Blob blob = rs.getBlob("image");
id = rs.getInt("id");
System.out.println(id);
System.out.println(blob);
System.out.println(blob.length());
InputStream in = blob.getBinaryStream(1, blob.length());
now it works for me
I have an item database (jdbc) the functionality is: insert, delete, and update using GUI JTable, all work good but I need to display the image in the JTable but I couldn't :(
If you could help me in that, here's the code for the main functionality:
fill Table method:
try{
connection= DriverManager.getConnection(url, usr, pas);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from item");
itemTable.setModel(DbUtils.resultSetToTableModel(resultSet));
} catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex);}
add method:
try{
PreparedStatement insert =connection.prepareStatement("INSERT INTO items"
+"(name, price, image, ID)"
+"VALUES(?,?,?,?)");
insert.setString(1, nameTextField.getText());
insert.setDouble(2, Double.parseDouble(priceTextField.getText()));
insert.setByte(3, image);
insert.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = insert.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
update method:
try{
PreparedStatement update =connection.prepareStatement("update item set "
+ "name=? , price=?, image=? where id=?""
+"VALUES(?,?,?,?)");
update.setString(1, nameTextField.getText());
update.setDouble(2, Double.parseDouble(priceTextField.getText()));
update.setByte(3, image);
update.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = update.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
delete method:
try{
Statement delete = connection.createStatement();
delete.executeUpdate("delete from item where id="+IDTextField.getText());
priceTextField.setText("");
nameTextField.setText("");
idTextField.setText("");
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
A button event to choose image from JFileChooser:
String imagePath = null;
JFileChooser file;
private void ChooseImageButtonActionPerformed(java.awt.event.ActionEvent evt){
int result = file.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
imagePath = path;
}
}
The important methods are fillTable() and add().
fillTable method could be like this:
//you need a TableModel, let´s call it model and let´s call your JTable myJTable
TableModel model = (javax.swing.table.DefaultTableModel) myJTable.getModel();
myJTable.setModel(model);
//try to add results
try {
connection = DriverManager.getConnection(url, usr, pas);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from item");
while (resultSet.next()) {
//after your query, get the Image
Blob blob = resultSet.getBlob(3);//column 3
byte[] data = blob.getBytes(1, (int) blob.length());
BufferedImage img = null;
img = ImageIO.read(new ByteArrayInputStream(data));
Icon imgToTable = imageToIcon(img);//use the method below
//add row to your table (throught the model)
model.addRow(new Object[]{resultSet.getObject(1).toString(), resultSet.getObject(2).toString(), imgToTable,resultSet.getObject(4).toString()});
//itemTable.setModel(DbUtils.resultSetToTableModel(resultSet));
}
resultSet.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
Add method could be like this:
try{
PreparedStatement insert =connection.prepareStatement("INSERT INTO items"
+"(name, price, image, ID)"
+"VALUES(?,?,?,?)");
insert.setString(1, nameTextField.getText());
insert.setDouble(2, Double.parseDouble(priceTextField.getText()));
//i recommend to use something like this to configure you image
file = new File(imagePath);
fis = new FileInputStream(file);
if (null == fis) {
fis = new FileInputStream(imagePath);
}
//configure image
insert.setBinaryStream(3, fis);
// insert.setByte(3, image);
insert.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = insert.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
And use this to convert from Image to Icon (to put it in a Table Cell):
//from Image a Icon
public Icon imageToIcon(Image image) {
ImageIcon imgIcon = new ImageIcon(image);
Icon iconReturn = (Icon) imgIcon;
return iconReturn;
}
If in your database you are not using blob let me know.
I am trying to select the image from a table which is retrieved from the database and then displays it as an icon on a label.
i found it difficult to convert object returned by getValueAt() method to bufferedImage object..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
pr=con.prepareStatement("SELECT `sender id`, `image`, `status` FROM `transfer` WHERE `receiver_id`=?");
pr.setString(1,jTextField3.getText());
rs=pr.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
}
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
try
{
int index=jTable1.getSelectedRow();
TableModel model=jTable1.getModel();
**BufferedImage ima=(BufferedImage) model.getValueAt(index,1);**
JLabel l=new JLabel(new ImageIcon(ima));
imagePane.getViewport().add(l);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
}
You should first convert blob to InputStream, and then to BufferedImage:
TableModel model=jTable1.getModel();
Blob myBlob = model.getValueAt(index, 1);
InputStream myIS = myBlob.getBinaryStream();
BufferedImage myImage = ImageIO.read(myIS);
I am trying display an array of bytes from a longblob image in a sql db and then make it into a BufferedImage and scale it to the size of my label, parts I know that work for sure is my SQL statement and the rescaling as I implemented it else where. I don't know if it is actually writing to the variable "image" or being made to icon then bufferedImage. im sure there is a way to make it a buffered image from the start but I am not too advanced with this part of java. any insight is helpful below is my code.
private void picPreviewerActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String vinNumber = vinInput.getText();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/newbieswithauctions","root","root");
PreparedStatement ps = con.prepareStatement("SELECT itemImage FROM images WHERE itemVin='"+ vinNumber + "'");
ResultSet rs = ps.executeQuery();
byte[] image = null;
while(rs.next()){
image = rs.getBytes("itemImage");
}
Image img = Toolkit.getDefaultToolkit().createImage(image);
ImageIcon icon = new ImageIcon(img);
Image pic = icon.getImage();
BufferedImage bufferedPic =(BufferedImage) pic;
try{
BufferedImage scaled = getScaledInstance(
bufferedPic, picView.getWidth(), picView.getHeight(), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
picView.setIcon(new ImageIcon(scaled));
}catch(Exception ex){
}
}
catch(Exception ex)
{
}
}
i have revised the code and i have this button and it will open a new form with the pic but nothing shows up this is the code in the button
private void picPreviewerActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String vinNumber = vinInput.getText();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/newbieswithauctions","root","root");
PreparedStatement ps = con.prepareStatement("SELECT itemImage FROM images WHERE itemVin='"+ vinNumber + "'");
ResultSet rs = ps.executeQuery();
byte[] image = null;
while(rs.next()){
image = rs.getBytes("itemImage");
}
InputStream in = new ByteArrayInputStream(image);
bufferedPic = ImageIO.read(in);
ImageIO.write(bufferedPic, "png", new File("C:\\Users\\geluna\\Desktop\\Software Engineering\\NWAGUI-sqlpicsworks\\NWAGUI-sqlpicsworks\\images\\newImage.png"));
}
catch(Exception ex)
{
}
new PicSearchWin().setVisible(true);
}
and in the form i have this in the main method so it populates the pic as soon as it opens but nothing happens but when i make a button in that form and put that code in there it will work when button is pressed. looks so bad. i want it to execute when form is opened. any ideas?
private void closeBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
}
private void btnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
BufferedImage NewBufferedPic = ImageIO.read(new File("C:\\Users\\geluna\\Desktop\\Software Engineering\\NWAGUI-sqlpicsworks\\NWAGUI-sqlpicsworks\\images\\newImage.png"));
BufferedImage scaled = getScaledInstance(
NewBufferedPic, pic.getWidth(), pic.getHeight(), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
pic.setIcon(new ImageIcon(scaled));
}catch(Exception ex){
JOptionPane.showMessageDialog(null,"GAY", "Error ", JOptionPane.ERROR_MESSAGE);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PicSearchWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PicSearchWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PicSearchWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PicSearchWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PicSearchWin().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btn;
private javax.swing.JButton closeBtn;
public static javax.swing.JLabel pic;
// End of variables declaration
}
Why do you require BufferedImage?
If you stored a BLOB then try this:
Blob blob = rs.getBlob("itemImage");
byte[] bytes = blob.getBytes(1, (int) blob.length());
Image myImage = Toolkit.getDefaultToolkit().createImage(bytes);
Image scaled = createYourScaledInstance();
picView.setIcon(new ImageIcon(scaled));
I am trying to add images to a rtf document. I am able to add images to the document but I can't append any images. This means that when the 2nd Image is added, the first image is removed. I think that whenever the code is executed a new rtf document is created.
public class InsertToWord {
com.lowagie.text.Document doc = null;
FileOutputStream evidenceDocument;
String fileName = "evidenceDocument.rtf";
settings obj = null;
InsertToWord() {
obj = new settings();
doc = new com.lowagie.text.Document();
}
public void insertImage(File saveLocation) {
try {
evidenceDocument = new FileOutputStream(obj.getFileLocation() + fileName);
RtfWriter2.getInstance(doc, evidenceDocument);
doc.open();
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(saveLocation.toString());
image.scaleAbsolute(400, 300);
doc.add(image);
doc.close();
} catch (Exception e) {
}
}
}
On your insertImage() method, you are indeed creating a new file and overwriting your old one.
This line is creating the new file:
evidenceDocument = new FileOutputStream(obj.getFileLocation()+fileName);
You can pass the FileOutputStream in as a parameter to the method and then remove the line all together:
public void insertImage( FileOutputStream evidenceDocument , File saveLocation )
This code is the one I´m using to add an image into a RTF format and its working fine :
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 200);
document = (StyledDocument) textPane.getDocument();
javax.swing.text.Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (option == JFileChooser.CANCEL_OPTION) {
fileChooser.setVisible(false);
}
}// End of Method
The textPane variable is a JTextPane.