Reputation: 539
I am attempting to process an image file and return it as an Image object, however I am getting an ArrayIndexOutOfBoundsException in the following code when I call public static BufferedImage getImageFromArray(int[] data, int columns, int rows).
I have the following pixel colors stored into an array named "data":
[255,6,65,78,99,100,25,0,45,66,88,190,88,76,50]
I parsed this out from a text file that looked like this:
255, 6, 65, 78, 99
100, 25, 0, 45, 66
88, 190, 88, 76, 50
I am trying to generate an image from this data by using BufferedImage currently I am hitting a brick wall with this. Columns and rows are passed to this based on the table structure above.
public static BufferedImage getImageFromArray(int[] data, int columns, int rows) {
BufferedImage image = new BufferedImage(columns, rows, BufferedImage.TYPE_INT_RGB);
WritableRaster raster = (WritableRaster) image.getData();
raster.setPixels(0,0, columns, rows, data);
image.setData(raster);
return image;
}
I get an OOB exception when I hit the raster.setPixels call. Does this need a different array or value I am missing?
Upvotes: 0
Views: 2299
Reputation: 539
Here is the solution I found, the type RGB requires 3 bands... therefore to create an array that works:
private int[] imageArray(String fullFilePath, int rows, int columns) throws Exception{
int picRows = rows;
int picColumns = columns;
data = getPixelData(fullFilePath);
//3 bands in TYPE_INT_RGB
int NUM_BANDS = 3;
int[] arrayImage = new int[picRows * picColumns * NUM_BANDS];
for (int i = 0; i < picRows; i++)
{
for (int j = 0; j < picColumns; j++) {
for (int band = 0; band < NUM_BANDS; band++)
for (int k = 0; k < data.length; k++)
arrayImage[((i * picRows) + j)*NUM_BANDS + band] = data[k];
}
}
return arrayImage;
}
Upvotes: 2