Thursday, July 2, 2009

Automatically Size to Fit Image in a JLabel

Images inside a Java Swing component do not automatically resize when it's larger than the component it resides in, resulting in a clipped image.

Oftentimes, it is convenient to have an image automatically resize to fit inside a component while preserving the aspect ratio. Thumbnail display is one that comes to mind.

It is actually fairly easy to implement this capability by extending JLabel and overriding the paintComponent() method:

protected void paintComponent(Graphics g)
{
ImageIcon icon = (ImageIcon) getIcon();
int iconWidth = icon.getIconWidth();
int iconHeight = icon.getIconHeight();
double iconAspect = (double) iconHeight / iconWidth;

int w = getWidth();
int h = getHeight();
double canvasAspect = (double) h / w;

int x = 0, y = 0;

// Maintain aspect ratio.
if(iconAspect < canvasAspect)
{
// Drawing space is taller than image.
y = h;
h = (int) (w * iconAspect);
y = (y - h) / 2; // center it along vertical
}
else
{
// Drawing space is wider than image.
x = w;
w = (int) (h / iconAspect);
x = (x - w) / 2; // center it along horizontal
}

Image img = icon.getImage();
g.drawImage(img, x, y, w + x, h + y, 0, 0, iconWidth, iconHeight, null);
}


Download Source Code

ThumbnailLabel.java

7 comments:

  1. Hi Daniel,

    I found this post via google - great solution to my current problem! Would you mind if I used it in a commercial software project? I'm not asking for any liabilities, of course, just an OK that I use the code as-is with no warranties that it'll work etc, even though the project is closed-source and commercial.

    ReplyDelete
    Replies
    1. Sorry for the laaaate response. The code is meant as a learning tool, of course. But it fits your needs, by all means, use it.

      Delete
  2. I am using this class for my images it is working perfectly with netbeans ide but problem occurs when I double click the app.jar file from dist folder then it is not working.

    ReplyDelete
    Replies
    1. If it works in NetBeans, it should work elsewhere. Do make sure that NetBeans and your OS are referring to the same version of JRE when running your program. It's possible that there are several version of JRE installed on the same system.

      Delete
  3. Please!Demo .I try run in my Project.but it not work.Help me.

    ReplyDelete
    Replies
    1. Need a little more detail than "it [sic] not work". What happened? And let me know a little more about your environment.

      Delete
  4. Great!! Works as is. Thank you!

    ReplyDelete