9

我想获得缓冲图像的缩放实例,我做到了:

public void analyzePosition(BufferedImage img, int x, int y){   
     img =  (BufferedImage) img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
....
}

但我确实有一个例外:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
    at ImagePanel.analyzePosition(ImagePanel.java:43)

我想然后转换ToolkitImage然后使用getBufferedImage我在其他文章中读到的方法。问题是没有诸如sun.awt.image.ToolkitImage我不能转换的类,因为 Eclipse 甚至没有看到这个类。我使用Java 1.7jre1.7

在此处输入图像描述

4

2 回答 2

17

您可以使用 TookitImage 创建一个新图像,即 BufferedImage。

Image toolkitImage = img.getScaledInstance(getWidth(), getHeight(), 
      Image.SCALE_SMOOTH);
int width = toolkitImage.getWidth(null);
int height = toolkitImage.getHeight(null);

// width and height are of the toolkit image
BufferedImage newImage = new BufferedImage(width, height, 
      BufferedImage.TYPE_INT_ARGB);
Graphics g = newImage.getGraphics();
g.drawImage(toolkitImage, 0, 0, null);
g.dispose();

// now use your new BufferedImage
于 2013-10-22T00:20:30.017 回答
6

BufferedImage#getScaledInstance实际上是继承自java.awt.Image并且只保证它将返回 anImage所以我想说在这种情况下尝试假设底层返回类型不是一个好主意。

getScaledInstance通常也不是最快或质量最好的方法

要缩放BufferedImage自身,您有许多不同的选项,但最简单的是获取原始图像并将其重新绘制到另一个图像,在过程中应用某种缩放。

例如:

有关更多详细信息getScaledInstance,请阅读Image.getScaledInstance() 的风险

于 2013-10-22T00:40:21.230 回答