如何获取缩放后的BufferedImage实例

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
2个回答

17

你可以使用ToolkitImage创建一个新的图像,即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

6

BufferedImage#getScaledInstance实际上是继承自java.awt.Image,并且只保证返回一个Image对象。因此,在这种情况下尝试并假定底层返回类型并不是一个好主意。

getScaledInstance通常也不是最快或最优质的缩放方法。

要缩放BufferedImage本身,你有许多不同的选项,但大多数都会将原始图像重新绘制到另一个图像上,并在过程中应用某种缩放。

例如:

更多关于getScaledInstance的详细信息,请参阅Image.getScaledInstance()的危险性


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接