开发者

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.


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜