How to get a scaled instance of bufferedImage

I wanted to get a 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 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) 

Then I needed to click ToolkitImage , and then use the getBufferedImage method, which I read about in other articles. The problem is that there is no class like sun.awt.image.ToolkitImage which I cannot use for it because Eclipse does not even see this class. I am using Java 1.7 and jre1.7 .

enter image description here

+7
java toolkit bufferedimage scale
source share
2 answers

You can create a new image, BufferedImage with 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 
+12
source share

BufferedImage#getScaledInstance is actually inherited from java.awt.Image and only guarantees that it will return Image , so I would say that it is not recommended to try and assume the return type in this case.

getScaledInstance also not usually the fastest or best quality.

To scale the BufferedImage itself, you have several different options, but the easiest way is to take the original and redraw it to another image, using some kind of scaling in the process.

For example:

  • Automatically scale ImageIcon to label size
  • Place image at any screen resolution
  • How to make the image stretchable in a swing?

For more information on getScaledInstance read The Perils of Image.getScaledInstance ()

+3
source share

All Articles