Difference between the Image and BufferedImage in Java

后端 未结 3 1189
难免孤独
难免孤独 2020-12-29 22:56

What is the difference between Image and BufferedImage?

Can I create a BufferedImage directly from an Image source \"image.png\"?

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 23:37

    Image is an abstract class. You can't instantiate Image directly. BufferedImage is a descendant, and you can instantiate that one. So, if you understand abstract classes and inheritance, you'll understand when to use each.

    For example, if you were using more than one Image descendant, they're going to share some common properties, which are inherited from Image.

    If you wanted to write a function that would take either kind of descendant as a parameter you could do something like this:

    function myFunction(Image myImage) {
      int i = myImage.getHeight();
      ...
    }
    

    You could then call the function by passing it a BufferedImage or a VolatileImage.

    BufferedImage myBufferedImage;
    VolatileImage myVolatileImage;
    ...
    myFunction(myVolatileImage);
    myFunction(myBufferedImage);
    

    You won't convert an Image to a BufferedImage because you'll never have an Image.

提交回复
热议问题