Question

I am trying to load an image from directory and place it as an icon in JLabel. But when the image size is big it doesn't fit completely in the label. I tried resizing the image to fit in the label but its not working. May I know where I am going wrong?

JFileChooser choose=new JFileChooser();
choose.showOpenDialog(null);
File f=choose.getSelectedFile();
String filename=f.getAbsolutePath();
path.setText(filename);

ImageIcon icon=new ImageIcon(filename);
Image img=icon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null),   BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(img,500, 500, null);
ImageIcon newIcon = new ImageIcon(bi);
image_label.setIcon(newIcon);
Was it helpful?

Solution

BufferedImage img = ImageIO.read(...);
Image scaled = img.getScaledInstance(500, 500, Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(scaled);

Beware, that this will scale the image so that it is square. Take a look at Java: maintaining aspect ratio of JPanel background image which discusses maintaining the aspect ratio of the image when scaled.

Also, you should read The Perils of Image.getScaledInstance() and have a look at Scale the ImageIcon automatically to label size which uses a divide and conqure scaling algorithim and Quality of Image after resize very low -- Java which demonstrates the issues of doing a one step scale...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top