Java converting Image to BufferedImage
There is already question like this link on StackOverflow and the accepted answer is "casting":
Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;
In my program I try:
final float FACTOR = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = (BufferedImage) image;
Unfortunatelly I get run time error:
sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
Obviously casting does not work.
Question is: What is (or is there) the proper way of converting Image to BufferedImage?
From a Java Game Engine:
/**
* Converts a given Image into a BufferedImage
*
* @param img The Image to be converted
* @return The converted BufferedImage
*/
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
One way to handle this is to create a new BufferedImage, and tell it's graphics object to draw your scaled image into the new BufferedImage:
final float FACTOR = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);
That should do the trick without casting.