1

I have 1D byte array for the buffered image.I want to convert it to the 2D byte array for that i have written the code as below

File file = new File("/home/tushar/temp.jpg");
try {
        input_bf = ImageIO.read(file);
        width = input_bf.getWidth();
        height = input_bf.getHeight();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
byte [][] image = new byte[width][height];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
        ImageIO.write(input_bf, "jpg", bos );
        bos.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

byte[] imageInByte = bos.toByteArray();
        try {
            bos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


//here is the main logic to convert 1D to 2D
int x=0;
for(int i=0;i<width;i++)
{
    for(int j=0;j<height;j++)
    {
        image[i][j] = imageInByte[x];
        x++;
    }
}

But i get the exception like

java.lang.ArrayIndexOutOfBoundsException: 26029
    at smoothing.main(smoothing.java:70)

The size of 1D array is 26029 which shows the exception.

Now what should i do?

How to convert the 1D to 2D image array?

or can any one know how to convert the image to 2D array?

1
  • That BufferedImage you have already give you access to individual pixels, if that is what you are after. A JPEG is compressed, and you cannot just pull out individual bytes.
    – Thilo
    Commented Sep 3, 2013 at 7:59

1 Answer 1

2

Instead of using ByteArrayOutputStream use DataBufferByte,it will work.

DataBufferByte db = (DataBufferByte)image.getRaster().getDataBuffer();

            byte[] pixelarray = db.getData();

and then apply the logic to convert the 1D array to 2D array

This gives the correct image size and avoid exception.

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.