如何获得bufferedImage的缩放实例
我想得到一个缓冲图像的缩放实例,我做了:
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
我无法sun.awt.image.ToolkitImage
转换它,因为Eclipse甚至没有看到这个类。 我使用Java 1.7
和jre1.7
。
您可以使用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
BufferedImage#getScaledInstance
实际上是从java.awt.Image
inheritance的,只保证它会返回一个Image
所以我想说在这种情况下尝试假设底层返回类型不是一个好主意。
getScaledInstance
通常也不是最快或最优质的方法
要缩放BufferedImage
本身,您有许多不同的选项,但大多数只是将原始图像重新绘制到另一个图像,在处理过程中应用某种缩放。
例如:
- 将ImageIcon自动缩放到标签大小
- 在任何屏幕分辨率中定位图像
- 如何使图像在swing中伸展?
有关getScaledInstance
更多详细信息,请阅读Image.getScaledInstance()的Perils