How to convert buffered image to image and vice-versa?

Arizvi picture Arizvi · Feb 3, 2012 · Viewed 112.8k times · Source

Actually i am working on a image editing software and now i want to convert the buffered-image i.e :

  BufferedImage buffer = ImageIO.read(new File(file));

to Image i.e in the format something like :

  Image image  = ImageIO.read(new File(file));

Is it possible to so?? If yes, then how??

Answer

MetroidFan2002 picture MetroidFan2002 · Feb 3, 2012

BufferedImage is a(n) Image, so the implicit cast that you're doing in the second line is able to be compiled directly. If you knew an Image was really a BufferedImage, you would have to cast it explicitly like so:

Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;

Because BufferedImage extends Image, it can fit in an Image container. However, any Image can fit there, including ones that are not a BufferedImage, and as such you may get a ClassCastException at runtime if the type does not match, because a BufferedImage cannot hold any other type unless it extends BufferedImage.