Resize a picture to fit a JLabel

I'm trying to make a picture fit a JLabel. I wish to reduce the picture dimensions to something more appropriate for my Swing JPanel.

I tried with setPreferredSize but it doesn't work.

I'm wondering if there is a simple way to do it? Should I scale the image for this purpose?

Answers


Outline

Here are the steps to follow.

  • Read the picture as a BufferedImage.
  • Resize the BufferedImage to another BufferedImage that's the size of the JLabel.
  • Create an ImageIcon from the resized BufferedImage.

You do not have to set the preferred size of the JLabel. Once you've scaled the image to the size you want, the JLabel will take the size of the ImageIcon.

Read the picture as a BufferedImage
BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}
Resize the BufferedImage
BufferedImage dimg = img.getScaledInstance(label.width, label.height,
        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.

Create an ImageIcon
ImageIcon imageIcon = new ImageIcon(dimg);

Need Your Help

create Wordperfect file using Corel SDK

c# .net wordperfect

We are trying to create a wordperfect files using Corel sdk(WPOX7 SDK) with .net (C#)frame work.

Redirect domain name mapped with external IP (modem) to a host in its local network

networking dns routing router

I have a modem that is connected to a router. There are two computers connected to this router. I want to set a domain for one of those computers so that I can access the web deployment server runn...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.