Bishwajit Purkaystha Bishwajit Purkaystha - 6 months ago 32
Java Question

Exception in BufferedImage.getData().getPixels()

I was looking to convert a buffered image to its corresponding pixel value array. I found a code for that:

public static double[] createArrFromIm(BufferedImage im){
int imWidth = im.getWidth();
int imHeight = im.getHeight();
double[] imArr = new double[imWidth* imHeight];
im.getData().getPixels(0, 0, imWidth, imHeight, imArr);
return imArr;
}


The original author who wrote this code block also gave some sample images which work perfect for this block. However, when I try to run this block against my images (the images are always 125*150) the block throws an array index out of bound exception at line:

im.getData().getPixels(0, 0, imWidth, imHeight, imArr);


This incident seems very arcane to me. Any help or suggestion will be very much appreciable. Thanks.

Answer

Do it using the raster:

public static double[] createArrFromIm(BufferedImage im){
    int imWidth = im.getWidth();
    int imHeight = im.getHeight();
    double[] imArr = new double[imWidth* imHeight];
    for (int y=0, nb=0 ; y < imHeight ; y++)
        for (int x=0 ; x < imWidth ; x++, nb++)
            imArr[nb] = im.getRaster().getSampleDouble(x, y, 0) ;
    return imArr;
}

As pointed by @haraldK, getData() also works, but it returns a copy of the raster, so it's slower.

There is a faster way using the DataBuffer, but then you have to manage the BufferedImage encoding because you have a direct access to the pixel values.