Convert Java to BufferedImage

StackOverflow already mentions such a link , 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; 

Unfortunately, I get a runtime error:

sun.awt.image.ToolkitImage cannot be attributed to java.awt.image.BufferedImage

Obviously casting is not working.
Question: what (or is) the correct way to convert Image to BufferedImage?

+56
java casting image bufferedimage
Nov 28 '12 at 12:37
source share
4 answers

From the 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; } 
+71
Nov 28 '12 at 12:47
source share

One way to deal with this is to create a new BufferedImage and tell the graphic to draw a scaled image in 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); 

This should do the trick without casting.

+16
Nov 28
source share

If you return to sun.awt.image.ToolkitImage , you can apply an image to it and then getBufferedImage () to get a BufferedImage .

So, instead of your last line of code in which you are casting, you simply do:

 BufferedImage buffered = ((ToolkitImage) image).getBufferedImage(); 
+2
Nov 28 '12 at 12:47
source share

If you use Kotlin, you can add the extension method to Image in the same way as Sri Harsha Chilakapati suggests.

 fun Image.toBufferedImage(): BufferedImage { if (this is BufferedImage) { return this } val bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB) val graphics2D = bufferedImage.createGraphics() graphics2D.drawImage(this, 0, 0, null) graphics2D.dispose() return bufferedImage } 

And use it as follows:

 myImage.toBufferedImage() 
0
Nov 27 '17 at 12:42 on
source share



All Articles