[英]Inserting a file into Jlabel with JFileChooser
Am trying to get a file(image) to fit into a Jlabel with JFileChooser. 我试图通过JFileChooser获取一个文件(图像)以适应Jlabel。 But it enlarges the Jlabel when i insert the file.
但是当我插入文件时,它会扩大Jlabel。
This is a sample of my codes... 这是我的代码示例......
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);
Try this code, it may helpful to you. 试试这段代码,它可能对您有所帮助。
Read the picture as a BufferedImage 将图片作为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();
}
Resize the BufferedImage 调整BufferedImage的大小
Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
Make sure that the label width and height are the same proportions as the original image width and height. 确保标签宽度和高度与原始图像宽度和高度的比例相同。 In other words, if the picture is 600 x 900 pixels, scale to 100 X 150. Otherwise, your picture will be distorted.
换句话说,如果图片为600 x 900像素,则缩放为100 X 150.否则,图片将会失真。
ImageIcon imageIcon = new ImageIcon(dimg)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.