Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 944
Arek Wilk Avatar asked Nov 28 '12 12:11

Arek Wilk


People also ask

What is the difference between image and BufferedImage in Java?

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.

What is BufferedImage in Java?

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).

How do I save BufferedImage in Java?

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) { ... }

How do I change a buffered image to an image?

You can use BufferImage's getScaledInstance() to scale BufferedImage in java. final int SCALE = 2; Image img = new ImageIcon("MyFile. png").


1 Answers

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; } 
like image 166
Sri Harsha Chilakapati Avatar answered Sep 20 '22 06:09

Sri Harsha Chilakapati