Peter C
Peter C

Reputation: 6307

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.

Upvotes: 1

Views: 1036

Answers (4)

Norayr Sargsyan
Norayr Sargsyan

Reputation: 1868

You can use this method also for seizing images

 public static void resize(final String inputImagePath, final String outputImagePath, final int scaledWidth, final int scaledHeight) throws IOException {
    final File inputFile = new File(inputImagePath);
    final BufferedImage inputImage = ImageIO.read(inputFile);

    final BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType());

    final Graphics2D g2d = outputImage.createGraphics();
    g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
    g2d.dispose();

    final String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1);

    ImageIO.write(outputImage, formatName, new File(outputImagePath));
}

Upvotes: 0

William
William

Reputation: 13642

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

Upvotes: 4

andrewmu
andrewmu

Reputation: 14534

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

Upvotes: 2

AdamH
AdamH

Reputation: 1378

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

Upvotes: 3

Related Questions