使用 Raster 创建图像时出现 ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException when creating an image using Raster

我正在尝试使用此数组创建图像: [-8421505, -8421505, -8421505, -8421505,...] 它的长度是:62416

BufferedImage img = new BufferedImage(166, 376, BufferedImage.TYPE_INT_RGB);
int pixels[] = new int[166 * 376];

这里应该是错误所在

img.getRaster().setPixels(0, 0, 166 , 376, pixels);

那我就存着吧

File file = new File("new.png");
ImageIO.write(img, "png", file);  

即:

ArrayIndexOutOfBoundsException : 62416

出于某种原因,尽管看起来 BufferedImage.TYPE_INT_RGB 每个像素应该有 1 个整数。当您使用 WritableRaster#setPixels 时,它实际上每个像素需要 3 个整数。

给定一些输入数据,

int[] values = {...};

其中每个int对应一个像素,RGB分别为8位。它们将需要放入更大的阵列中,然后解压。

int pixels[] = new int[values.length*3];
for(int i = 0; i<values.length; i++){
   pixels[3*i] = (values[i]>>16)&0xff;
   pixels[3*i+1] = (values[i]>>8)&0xff;
   pixels[3*i+2] = (values[i])&0xff;
}

我通过创建一个包含红色、绿色和蓝色的值数组来检查这一点。

int[] values = new int[166*376];
for(int i = 0; i<166*125; i++){
    values[i] = 0xff0000; //red
}
for(int i = 166*125; i<166*250; i++){
    values[i] = 0xff00; //green
}
for(int i = 166*250; i<166*376; i++){
    values[i] = 0xff; //blue
}