Search code examples
javaimage-processingimage-resizing

How do I resize an image with Java?


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.


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