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?
If you are familiar with Java's util. List, the difference between Image and BufferedImage is the same as the difference between List and LinkedList. Image is a generic concept and BufferedImage is the concrete implementation of the generic concept; kind of like BMW is a make of a Car.
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).
The formatName parameter selects the image format in which to save the BufferedImage . try { // retrieve image BufferedImage bi = getMyImage(); File outputfile = new File("saved. png"); ImageIO. write(bi, "png", outputfile); } catch (IOException e) { ... }
You can use BufferImage's getScaledInstance() to scale BufferedImage in java. final int SCALE = 2; Image img = new ImageIcon("MyFile. png").
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With