繁体   English   中英

使用JFileChooser将文件插入Jlabel

[英]Inserting a file into Jlabel with JFileChooser

我试图通过JFileChooser获取一个文件(图像)以适应Jlabel。 但是当我插入文件时,它会扩大Jlabel。
这是我的代码示例......

JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
btnInsert.setText(filename);
ImageIcon icon = new ImageIcon(filename);
lblPic.setIcon(icon);

试试这段代码,它可能对您有所帮助。

将图片作为BufferedImage读取

 BufferedImage img = null;
 JFileChooser chooser = new JFileChooser();
 chooser.showOpenDialog(null);
 File file = chooser.getSelectedFile();
 try {
     img = ImageIO.read(file );
 } catch (IOException e) {
     e.printStackTrace();
 }

调整BufferedImage的大小

Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);

确保标签宽度和高度与原始图像宽度和高度的比例相同。 换句话说,如果图片为600 x 900像素,则缩放为100 X 150.否则,图片将会失真。

ImageIcon imageIcon = new ImageIcon(dimg)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM