Search code examples
javaimagebufferedimage

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


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??


Solution

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