Java converting Image to BufferedImage

Arek Wilk picture Arek Wilk · Nov 28, 2012 · Viewed 163.3k times · Source

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?

Answer

Sri Harsha Chilakapati picture Sri Harsha Chilakapati · Nov 28, 2012

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;
}