Search code examples
javaimagegraphicspixel

BufferedImage pixels Vs Graphics.drawImage


What is the difference between making a Buffered Image, and drawing on its pixels using:

private BufferedImage img;
private int[] pixels;

pixels = ((DataBufferInt) img.getRaster().getDataBuffer());

And just using a Image for the

img

Variable And using img's graphics to do:

img.getGraphics().drawImage(/*image*/, x, y, observer);

EDIT:

This is for game development!!


Solution

  • Advantages of going via the Graphics methods:

    • It's usually simpler to use the ready-made higher level operations like drawImage
    • You may benefit from hardware acceleration / optimisations on some platforms
    • It works relatively independently of the underlying image format

    Advantages of going down to the pixel buffer level:

    • It can be useful for very specialised purposes, e.g. generating each pixel from some sort of formula / calculation (I use this technique to generate custom colour gradients, for example)
    • It can be marginally faster for individual pixel operations (but likely to be slower for bulk operations like drawImage, because you don't get the hardware acceleration)

    If it's just regular in-game rendering of a screen, I'd say the Graphics route is probably best. If you're doing something fancy like on-the-fly image generation, then the pixel buffer route can be worth exploring.