BufferedImage is automatically updated when int-array representing its raster is updated

StackOverflow https://stackoverflow.com/questions/19940915

  •  30-07-2022
  •  | 
  •  

Question

I'm following a tutorial to expand my knowledge, but the tutor is sometimes of the mindset that some things need not be explained.

take a look at this code:

private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

someMethod() {
  for (int i=0; i<pixels.length; i++) {
    pixels[i] = i;
  }
  g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}

I paint on a Canvas and to my big surprise this will paint colors from black to blue. I wonder how to access/modify colors red and green (since the "pixels" is an array of single integers). if I replace RGB with BGR, this color will be red instead. But that's a sidenote. EDIT: to paint green and red use bitshift operators << and |. for instance: int greenColor = 255<<16; or int greenAndRed = 255<<16 | 255<<8; EDIT-END

The one major puzzle here is why anything is painted at all. How does assigning values to the pixels array update image? (I don't understand the field declaration at all. What the array is initiated to, that is). But my knowledge of Java tells me that is irrelevant. It is an ordinary int-array, with ordinary ints. Can someone tell me what's going on?

EDIT Question has been resolved. It is actually no big surprise that the image data changes at all since arrays are not immutable like the other simple data-types.

Was it helpful?

Solution

The raster is the backing datamodel of the image. The int[] pixels you are getting here is a reference to that backing data. Changing a value in the pixel array is actually changing the value of the backing data, immediately visible in the image.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top