为什么我不能更改此 BufferedImage?
Why can't I change this BufferedImage?
出于某种原因,我可以使用 setRGB 更改缓冲图像,但不能使用光栅中的实际 int 数组:
这个有效
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);
}
}
这不
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;
}
}
噪声函数:
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));
}
编辑
没关系,我修好了。我需要使用 getRaster :P
答案是否可以像数据数组中的更改未反映在 img
对象中一样简单?
因为当您调用 BufferedImage.getData()
时,它返回的是一个副本,而不是实际的后备数组。因此,您直接对该数组所做的任何更改都不会反映在图像中。
来自JavaDoc for BufferedImage.getData():
Returns:
a Raster that is a copy of the image data.
编辑 有趣的是它在Java 6 JavaDoc中对相同方法的说明,它更明确地说明了副本的效果。我想知道他们为什么要更改它?
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
出于某种原因,我可以使用 setRGB 更改缓冲图像,但不能使用光栅中的实际 int 数组:
这个有效
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);
}
}
这不
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;
}
}
噪声函数:
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));
}
编辑
没关系,我修好了。我需要使用 getRaster :P
答案是否可以像数据数组中的更改未反映在 img
对象中一样简单?
因为当您调用 BufferedImage.getData()
时,它返回的是一个副本,而不是实际的后备数组。因此,您直接对该数组所做的任何更改都不会反映在图像中。
来自JavaDoc for BufferedImage.getData():
Returns: a Raster that is a copy of the image data.
编辑 有趣的是它在Java 6 JavaDoc中对相同方法的说明,它更明确地说明了副本的效果。我想知道他们为什么要更改它?
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