name
name

Reputation: 362

Why can't I change this BufferedImage?

For some reason, I can change a buffered image by using setRGB but not by using the actual int array in the raster:

This works

BufferedImage img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB);

for (int y = 0; y < 32; y++) {
    for (int x = 0; x < 32; x++) {
        int gray = (int) (MathUtil.noise(x, y) * 255); //I have tested the noise function,   and know it works fine
        img.setRGB(x, y, gray << 16 | gray << 8 | gray);
    }
}

This does not

BufferedImage img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB);
int[] data = ((DataBufferInt) img.getData().getDataBuffer()).getData();

for (int y = 0; y < 32; y++) {
    for (int x = 0; x < 32; x++) {
        int gray = (int) (MathUtil.noise(x, y) * 255); //I have tested the noise function, and know it works fine
        data[x + y * 32] = gray << 16 | gray << 8 | gray;
    }
}

Noise function:

public static float noise(int x, int y) {
    int n = x + y * 57;
    n = (n << 13) ^ n;
    return Math.abs((1.0f - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0f));
}

EDIT

Nevermind I fixed it. I needed to use getRaster :P

Upvotes: 2

Views: 121

Answers (2)

Todd
Todd

Reputation: 31710

Because when you call BufferedImage.getData() it is returning a copy, not the actual backing array. So any changes you make directly to that array will not be reflected in the image.

From the JavaDoc for BufferedImage.getData():

Returns: a Raster that is a copy of the image data.

Edit What's interesting is what it says for the same method in the Java 6 JavaDoc, it's more explicit about the copy's effects. I wonder why they changed it?

Returns the image as one large tile. The Raster returned is a copy of the image data is not updated if the image is changed

Upvotes: 3

Rgw3d
Rgw3d

Reputation: 61

Could the answer be as simple as the changes in the data array not being reflected in img object?

Upvotes: 0

Related Questions