Search code examples
javagraphicsbufferedimagebufferstrategy

Java: Applying BufferedImage to BufferStrategy


I am currently learning from a GameDev tutorial and what really confuses me is how a BufferedImage that you raster into an array is being updated. In my code I never specified that a certain BufferedImage is supposed to be used for the BufferStrategy, which changes the Buffers by itself I guess, but the code still somehow works.

http://pastie.org/private/un1ep4wwrbsi0ecwmqc5w#15

I mean just ctrl+f for "image" and you see that the parameter "image" is never being updated; only created once and that is it. Yet, when the pixel-array is being changed (in a different class and copied to the one I posted), the changes affect the image-Object, which is then drawn by Graphics. Where exactly do I tell the JVM to copy the array-raster back to the BufferedImage (= parameter image)?


Solution

  • You don't need to copy the array back. The BufferedImage already has it. :-)

    I.e. the BufferedImage image shares the pixels array with the Game instance. The line:

    private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
    

    ....does not copy any data, it simply assigns a reference to the internal pixel data of image. Any changes in pixels will be reflected in image and vice versa.