views:

49

answers:

3

I have a bunch of 48x48 images that I need 16x16 versions of, and instead of storing the 16x16 versions, I want to resize them on the fly. My current code looks like this (model.icon() returns the 48x48 image):

Icon icon = model.icon();
Image image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
return new ImageIcon(image.getScaledInstance(16, 16, Image.SCALE_AREA_AVERAGING));

Unfortunately, when this code is run, I get a 16x16 black square instead of the image.

+3  A: 

You need more information than just the Icon reference. You need access to the actual image. You're new image is a black square because you never set the source if the image (i.e. you create a new black image and then scale the empty image).

AdamH
Thank you, but how do I transfer the image data from the icon to the image?
alpha123
+4  A: 

Try this.

ImageIcon icon = model.icon();
Image image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(icon.getImage(), 0, 0, 16, 16, null);
return new ImageIcon(image);
William
Ah ha! Thanks! That's it!
alpha123
Er, the only problem is that `Graphics.drawImage()` takes an `Image` instead of an `Icon`.
alpha123
Yes, you are correct - I've justed updated my code - you need to call icon.getImage(), as you've probably realised from andrewmu's answer :)
William
+1  A: 

You are not putting the Icon into the Image. If icon is an ImageIcon, then you can do:

..
Graphics2D g2 = image.createGraphics();
g2.drawImage(icon.getImage(), 0, 0, 16, 16, null);
g2.dispose();
return new ImageIcon(image);
andrewmu
Also, to improve the appearance, before you draw the image into g2, you can do: `g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHint.VALUE_INTERPOLATION_BICUBIC)` to get better quality output.
andrewmu
Thanks. This answer + the answer I marked as the solution helped.
alpha123