user2558479
user2558479

Reputation: 35

resizing image to fit exactly Jlabel of 300 by 300 px

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

Upvotes: 1

Views: 975

Answers (2)

Zoka
Zoka

Reputation: 445

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

Upvotes: 1

kiheru
kiheru

Reputation: 6618

getScaledInstance() does not modify the original image. Do

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

instead.

Upvotes: 2

Related Questions