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
Hi Daniel,
ReplyDeleteI 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.
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.
DeleteI 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.
ReplyDeleteIf 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.
DeletePlease!Demo .I try run in my Project.but it not work.Help me.
ReplyDeleteNeed a little more detail than "it [sic] not work". What happened? And let me know a little more about your environment.
DeleteGreat!! Works as is. Thank you!
ReplyDelete