Why doesn't this code resize the image according to the jLabel size? Why doesn't the image fit into the jLabel? What did I do wrong? After studying lots of code snippets about image resizing, here is the code I have done so far,
private void btn_browseActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
filename = f.getAbsolutePath();
try {
BufferedImage img = ImageIO.read(new File(filename));
int width = lbl_img.getWidth();
int height = lbl_img.getHeight();
Image image = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
buffered.getGraphics().drawImage(image, 0, 0, null);
ImageIcon imageIcon = new ImageIcon(buffered);
lbl_img.setIcon(imageIcon);
txt_imgpath.setText(filename);
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
} {
person_image = bos.toByteArray();
}
} catch(IOException ex) {
Logger.getLogger(FoodsJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private ImageIcon format = null;
String filename = null;
byte[] person_image = null;
This code doesn't show any exception but doesn't work as I wanted. It displays the image as it's actual size,big or small. Not as the jLabel's size. Sorry for this kind of newbie type question. I am just a beginner of Java. I tried a lot but can't figure out the solution. Anyone please help me.
Edit: While retrieving data by clicking data from jTable or by searching through jTextField, the image display as it's actual size,big or small. Not as the jLabel's size. Do I need something to do in that code too? Here is the code,
private void tbl_foodsMouseClicked(java.awt.event.MouseEvent evt) {
int raw = tbl_foods.getSelectedRow();
String Table_Click = (tbl_foods.getModel().getValueAt(raw, 0).toString());
try
{
String sql = "Select Image from Product_food where ID='"+Table_Click+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next())
{
byte[] imagedata = rs.getBytes("Image");
format = new ImageIcon(imagedata);
lbl_img.setIcon(format);
}
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
String sql = "Select * from Product_food where ID='"+Table_Click+"' ";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next())
{
String add1 = rs.getString("ID");
txt_proid.setText(add1);
String add2 = rs.getString("Name");
txt_name.setText(add2);
Double add3 = rs.getDouble("Price");
txt_price.setText(Double.toString(add3));
Date add4 = rs.getDate("Date");
txt_adddate.setDate(add4);
byte[] add5 = rs.getBytes("Image");
format = new ImageIcon(add5);
lbl_img.setIcon(format);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}