Daniel Searson wrote:Ok, here's one way of doing it.
You load your image straight into the ImageIcon using the constructor that takes a file name as an argument like:
ImageIcon icon = new ImageIcon("whatever.jpg");
Make sure the reference you create is an ImageIcon reference. Then use getImage() to grab the image from the ImageIcon:
Image img = icon.getImage();
Now create a buffered image the same size as the image:
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Then blit the icon image to the buffered image, and resize it as you do so:
Graphics g = bi.createGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
(The code above may be incorrect - check the docs)
Now recreate the IconImage with the new buffered image:
IconImage newIcon = new IconImage(bi);
Hope that helps.
- Daniel
I like this option. All of the posts I have read elsewhere recommend using the BufferedImage/Graphics.drawImage approach.
In this situation, it looks like you do actually need a resized image. In the project I am working on, I have been using a modified JLabel to use a resized icon. You may not need the whole IconLabel class, but it does implement the resize technique mentioned above. For added bonus (and for satisfying my OCD), I have pieced together some logic that also scales the image to within a certain size, maintaining its aspect ratio (i.e., I used
http://stackoverflow.com/questions/10245220/java-image-resize-maintain-aspect-ratio). That way, you can pre-determine how big of a space you want your image to take without compromising its aspect ratio. The getScaledDimension is taken from that URL, and it does a better job of explaining how it resizes an image and maintains its aspect ratio.
In this JLabel-extending class, the real tricks are to override getPreferredSize and the paintComponent methods, where I do the image resizing.