Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get scaled instance of a bufferedImage

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.

enter image description here

like image 555
Yoda Avatar asked Oct 22 '13 00:10

Yoda


People also ask

How do I change an image to BufferedImage?

BufferedImage buffer = ImageIO. read(new File(file)); to Image i.e in the format something like : Image image = ImageIO.

What does BufferedImage mean?

A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0).

What is the difference between BufferedImage and image?

A BufferedImage is essentially an Image with an accessible data buffer. It is therefore more efficient to work directly with BufferedImage. A BufferedImage has a ColorModel and a Raster of image data. The ColorModel provides a color interpretation of the image's pixel data.


1 Answers

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
like image 149
Hovercraft Full Of Eels Avatar answered Nov 03 '22 02:11

Hovercraft Full Of Eels