Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

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).

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top