Java.lang.classcastexception trying to convert blob to bufferedImage variable - java

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);

Related

Fetching image from database and directly read it into panel

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.

Swing: how get active JInternalFrame

I have problem with getting active JInternalFrame. I need to indicate an active ImageInternalFrame(my class, thats extend JInternalFrame) because I will perform some operations on it. I do not know how to solve it, can somebody help me?
Here is my code:
public class MainFrame extends javax.swing.JFrame {
ArrayList <ImageInternalFrame> imageInternalFrameList = new ArrayList();
private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filePath = f.getPath();
BufferedImage bufferedImage;
ImageInternalFrame imageInternalFrame;
String mimetype= new MimetypesFileTypeMap().getContentType(f);
String type = mimetype.split("/")[0];
if(type.equals("image")){
bufferedImage = null;
try {
bufferedImage = ImageIO.read(new File(filePath));
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
imageInternalFrame = new ImageInternalFrame(filePath);
imageInternalFrame.setSize( bufferedImage.getWidth(), bufferedImage.getHeight() );
imageInternalFrame.setVisible(true);
imageInternalFrame.setLocation(imageInternalFrameList.size() * 25 , imageInternalFrameList.size() * 25);
add(imageInternalFrame);
imageInternalFrameList.add(imageInternalFrame);
}
else{
JOptionPane.showMessageDialog(null, "It's NOT an image");
}}
public class ImageInternalFrame extends javax.swing.JInternalFrame {
public ImageInternalFrame( String imagePath ) {
initComponents();
setImage(imagePath);
}
public void setImage(String imagePath){
imageLabel.setIcon( new ImageIcon(imagePath) );
imageLabel.paintImmediately(imageLabel.getVisibleRect());
}
}
You can use the getSelectedFrame() method of your JDesktop class.
imageLabel.setIcon( new ImageIcon(imagePath) );
imageLabel.paintImmediately(imageLabel.getVisibleRect());
Don't use paintImmeditately. Swing will automatically schedule the repainting of the label when you change the Icon.

how to make a LONGBLOB image from SQL into a buffered image for displaying in a label

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));

How to improve the performance of JTextPane when loading large files

I want to load a large file(1MB of plain text) contents using JTextPane. It took nearly two minutes to load a large file. I want to load the large file into JTextPane within seconds. If it possible to improve the performance of the JTextPane. My Open action code is available in openActionPerformed() method. Please check it and give me some suggestions. Thank you.
Constructor code:
public class OpenDemo extends javax.swing.JFrame {
JTextPane textPane;
JScrollPane scrollPane;
int i=0;
public OpenDemo() {
initComponents();
textPane=new JTextPane();
}
OpenActionPerformed() method:
private void openActionPerformed(java.awt.event.ActionEvent evt) {
int offset = 0;
FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
fd.setVisible(true);
String title;
String path;
Path filePath = null;
File file;
if (fd.getFile() != null) {
path = fd.getDirectory() + fd.getFile();
file=new File(path);
filePath=file.toPath();
title=fd.getFile();
JInternalFrame internalFrame = new JInternalFrame("",true,true);
i++;
internalFrame.setName("Doc "+i);
internalFrame.setTitle(title);
scrollPane=new JScrollPane(textPane);
internalFrame.add(scrollPane);
tp.add(internalFrame);
myOffsetTextField=new JTextField();
List<String> allLines = null;
try {
allLines = Files.readAllLines(filePath, Charsets.UTF_8);
}
catch (MalformedURLException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
try{
offset = Integer.parseInt(myOffsetTextField.getText());
}
catch(NumberFormatException ne){
}
int numberOfLinesToShow = 10000;
int start = Math.min(allLines.size(), offset);
int end = Math.min(allLines.size(), start + numberOfLinesToShow);
List<String> sublist = allLines.subList(start, end);
textPane.setText(Joiner.on('\n').join(sublist));
textPane.setCaretPosition(0);
}
Main method:
public static void main(String args[]) {
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(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenDemo().setVisible(true);
}
});
}
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tp;
}
For a 1 MB text file it's impossible to take two minutes to load unless it's read from a diskette or alike.
Putting it all into a user interface is a non-sense, nobody can do anything with it. Scrolling using a scroll bar get completely unusable, too. Allow the user to enter a starting offset (in lines), read the file using Files.readLines into a List<String>, and display a few lines only.
Code idea
All non-JDK classes come from Guava.
List<String> allLines = Files.readLines(file, Chatsets.UTF8);
int offset = Integer.parseInt(myOffsetTextField.getText());
int numberOfLinesToShow = 10000;
int start = Math.min(allLines.size(), offset);
int end = Math.min(allLines.size(), start + numberOfLinesToShow);
// a sane-sized list of at most `numberOfLinesToShow` lines
List<String> sublist = allLines.sublist(start, end);
textPane.setText(Joiner.on('\n').join(sublist));

Image saving in database from jLabel

I have write the code below. I can choose image using FileChooser clicking button a button(jButton5) on a Label(jLabel4). Now I want to save the imagePath in database clicking another button(jButton1). Which code should I write for jButton1.
Someone please help me.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(this);
File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
jLabel4.setIcon(new ImageIcon(path));
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
}
If you want to store file location into database
Upload the file to some location.
Get uploaded file path
store that file path into some table.
If you want to store Images directly into Databse
Create table like below (MySql)
CREATE TABLE `IMAGES` (
`ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`IMAGE` LONGBLOB NOT NULL,
PRIMARY KEY(`ID`)
)
TYPE = InnoDB;
In your actionlistener
PreparedStatement ps = null;
InputStream is = null;
try {
con = // get your database connection
ps = con.prepareCall("insert into IMAGES values (?)");
is = new FileInputStream(new File("file path"));
ps.setBinaryStream(1, is);
int count = ps.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally{
try{
if(is != null) is.close();
if(ps != null) ps.close();
if(con != null) con.close();
} catch(Exception ex){}
}

Categories