Reputation: 65
I have a fixed size label to display image. How do I have the image resized to fit into the label, filled up. My current code below, is setting the label to the image size, I want it the other way round.
ImageIcon icon = new ImageIcon(bi);
Label.setIcon(icon);
Dimension imageSize = new Dimension(icon.getIconWidth(), icon.getIconHeight());
Label.setPreferredSize(imageSize);
Label.revalidate();
Label.repaint();
Upvotes: 2
Views: 1930
Reputation: 324197
You can use Darryl's Stretch Icon. The Icon will resize based on the space available to the label.
Upvotes: 2
Reputation: 929
So if you have a fixed size label, you can simple read image as BufferedImage object and then scale it to size of your label. After that you can create an icon and set it as JLabel's icon. Below code should work:
File imageFile = new File("image.jpg");
BufferedImage bufImg = null;
try {
bufImg = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
BufferedImage scaledImg = bufImg.getScaledInstance(Label.width, Label.height, Image.SCALE_SMOOTH);
Label.setIcon(new ImageIcon(scaledImg));
Upvotes: 0