I wanted to get scaled instance of a buffered image and I did:
public void analyzePosition(BufferedImage img, int x, int y){
img = (BufferedImage) img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
....
}
but I do get an exception:
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)
I wanted then to cast to ToolkitImage
then use the method getBufferedImage
I read about in other articles. The problem is there is no class such as sun.awt.image.ToolkitImage
I cannot cast to it because Eclipse does not even see this class. I use Java 1.7
and jre1.7
.
You can create a new image, a BufferedImage with the TookitImage.
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
is actually inherited from java.awt.Image
and only guarantees that it will return an Image
so I would say it's not a good idea to try and assume the underlying return type in this case.
getScaledInstance
is, also, not normally the fastest or best quality method
To scale a BufferedImage
itself, you have a number of different options, but most simply take the original and repaint it to another image, applying some kind of scaling in process.
For example:
- Scale the ImageIcon automatically to label size
- Position Image in any Screen Resolution
- how to make image stretchable in swing?
For more details about getScaledInstance
, have a read of The Perils of Image.getScaledInstance()
来源:https://stackoverflow.com/questions/19506927/how-to-get-scaled-instance-of-a-bufferedimage