Pages

Thursday, May 13, 2010

How to resize ImageIcon - Java

Please make reading a habit :)

 This was my problem before. After  days of searching, I combined the codes of my search items and came up with this:

-- start of function. I put it inside a function --


//gets the directory of the file
//this means that the file name is where the directory is plus the folder pictures plus the filename
//which is hold by the string named idnumber

idnumber = "CO00001";
dir_pic = System.getProperty("user.dir"); 
dir_pic = dir_pic+"\\Pictures\\"+idnumber+".jpg";

//you could simply put the path of the image in dir_pic variable

//We should have an image first.
//For me, I open the image from my directory
File file = new File(dir_pic); 
image = ImageIO.read(file); //reads the image

//this sets the image to an Image Icon
ImageIcon icon = new ImageIcon(image);

//we start to scale here
//first get the image from ImageIcon
Image img = icon.getImage();
//then scale it; I scaled it to 120x120
//please check the documentation for parameter listing if u dont want SCALE_SMOOTH
Image newimg = img.getScaledInstance(120, 120,java.awt.Image.SCALE_SMOOTH); 
newIcon = new ImageIcon(newimg); //we now have new icon - scaled by 120x120

//I made a JLabel named label and put the image there
label = new JLabel(new ImageIcon(newimg)); 
//then put the label to a square panel
picpanel.add(label); 
label.setBounds(2, 2, 115, 105); //change the bounds according to your design


--- end of function ---

For questions, post a comment to this post... :)

1 comments:

Rohit said...

Thanks alot ... it really helped me :)

Post a Comment