Am trying to get a file(image) to fit into a Jlabel with JFileChooser. But it enlarges the Jlabel when i insert the file.
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 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
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.
ImageIcon imageIcon = new ImageIcon(dimg)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.