Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
307 views
Welcome To Ask or Share your Answers For Others

1 Answer

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...