Search code examples
javabufferedimagegraphics2d

Why use BufferedImage over Graphics2D?


I've viewed several guides in Java game development and some of them modify a BufferedImage then display that to a Canvas. My question is, why not directly paint the image to the Canvas using Graphics2D? Why are we using a BufferedImage as a "3rd party" of a sort. Is there a benefit to this or could it be BufferedImages are used primarily for when you're working with an manipulating individual pixels?


Solution

  • You can obtain a Graphics2D from any BufferedImage using

    Graphics2D g = (Graphics2D)bufferedImage.getGraphics();
    

    That way, you can use all the painting capabilities of Java2D and still have a BufferedImage with all its benefits (convolve operations, pixel manipulation, recomposition effects for transitions (e.g. fade) between game screens).

    Swing's JComponent and its subclasses already provide double buffering capabilities, so you're right, you don't exactly need an extra BufferedImage for that. The differnce is that Swing repaints regions when they get dirty (for example when you move another window over your game viewport), this might interfer with your game updating the screen at regular (realtime) or controlled (for event-based games) intervals, so you might be better off using that extra buffer.