0

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?

3
  • 3
    An AIOOBException will be thrown by WritableRaster#setPixels if "if the coordinates are not in bounds, or if iArray is too small to hold the input." You can eliminate the first cause, and therefore deduce that the data array is smaller in size than columns*rows. I recommend debugging your values. Commented Oct 31, 2012 at 21:10
  • Within the WriteableRaster I do see maxX = 5 and maxY = 3 being set within raster, I am unclear of how to set this array to the appropriate size. Commented Oct 31, 2012 at 21:25
  • Why a downvote, I dont get it ? Its a valid question and well written. Commented Nov 1, 2012 at 2:52

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.