Question

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

Was it helpful?

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.

OTHER TIPS

  • Using getGraphics() provides a reliable way to draw on an image regardless of its underlying structure.
  • Note that you should not do this via chaining as you demonstrate: img.getGraphics().drawImage(/*image*/, x, y, observer); since this does not allow you to dispose of the Graphics object once you're done with it, risking your running out of resources.
  • Directly manipulating your raster's bits is possibly a quicker way to change things, but I believe that how you do this is dependent on the type of BufferedImage you are using.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top