1

I am retrieving an image from database that is needed to be fitted inside the JLabel of size 300 by 300. In this code the image is not resized instead a part of it is displayed inside the JLabel:

ResultSet r;

r = s.executeQuery("select * from  employee where emp_name='"+user+"'");

boolean v=r.next();
if (v==true) {
    add(r.getString("designation"));//to call add function 


    InputStream is = r.getBinaryStream(3);
    BufferedImage bimg = ImageIO.read(is);


    bimg.getScaledInstance(300,300,Image.SCALE_SMOOTH);

    ImageIcon n=new ImageIcon();
    n.setImage(bimg);

    l[1].setIcon(n);
}   
kiheru
  • 6,588
  • 25
  • 31
  • You can also look at this [alternative approach](http://stackoverflow.com/a/6916719/1057230), as mentioned in an answer. – nIcE cOw Jul 20 '13 at 13:29

2 Answers2

2

getScaledInstance() does not modify the original image. Do

Image bimg = ImageIO.read(is);
bimg = bimg.getScaledInstance(300,300,Image.SCALE_SMOOTH);

instead.

kiheru
  • 6,588
  • 25
  • 31
  • i tried it but the error is sun.awt.image.toolkit cannot be cast to java.awt.image.BufferedImage – user2558479 Jul 20 '13 at 13:16
  • ToolkitImage? That is possible. I changed the answer to work without the cast. – kiheru Jul 20 '13 at 13:26
  • +!, seems like this should work :-), though I am not the guy who knows how to handle images, that well, in Swing :-) – nIcE cOw Jul 20 '13 at 13:30
  • @user2558479 Just that the error likely was not for `sun.awt.image.toolkit`, but `sun.awt.image.ToolkitImage`. Anyway, the answer does not require a cast anymore, and should work – kiheru Jul 20 '13 at 16:16
1

Let's say your BLOB column name is 'picture'.

public void ReadImage(String user, JLabel jl){
        try{

            String query = "SELECT picture FROM employee WHERE emp_name='"+user+"'";
            pst = con.prepareStatement(query);
            rs = pst.executeQuery();

            byte[] imageData = rs.getBytes(1);
            ImageIcon ii = new ImageIcon(imageData);
            Image image = ii.getImage();
            image = image.getScaledInstance(300, 300, Image.SCALE_SMOOTH);
            ii = new ImageIcon(image);
            jl.setIcon(ii);

        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }
    }
Zoka
  • 393
  • 3
  • 14