调整图像大小以适合JLabel

时间:2014-03-27 06:17:51

标签: java image swing jlabel imageicon

我正在尝试从目录加载图片并将其作为图标放在JLabel中。但是当图像尺寸很大时,它并不完全适合标签。我尝试调整图像大小以适应标签,但它不起作用。我可以知道我哪里出错吗?

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

1 个答案:

答案 0 :(得分:1)

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

请注意,这会缩放图像以使其为正方形。请查看Java: maintaining aspect ratio of JPanel background image,其中讨论了在缩放时保持图像的纵横比。

另外,您应该阅读The Perils of Image.getScaledInstance()并查看Scale the ImageIcon automatically to label size,其中使用了除法和缩放算法以及Quality of Image after resize very low -- Java,它展示了一步缩放的问题......