-1

I'm trying to read a byte array of an image using the following code but it throws an out of memory exception. I have commented where the exception occurs.

byte[] bBuffer = new byte[300000]; // 
ByteArrayBuffer baf = new ByteArrayBuffer(300000);
int total = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
    int read = 0;           
    while ((dis.read(bBuffer, 0, bBuffer.length)) != -1) {
        baos.write(bBuffer, 0, bBuffer.length); // Exception occurs here        
        Log.d("outputImageBytes", "Reading Image Bytes: " + bBuffer.length + " " + read++ );
    }
    //baos.flush();
}
catch (Exception e)
{   
    Log.e("outputImageBytes", "Exception Occured while reading image bytes: " + e.getMessage());
    e.getMessage();
}
Adam
  • 35,919
  • 9
  • 100
  • 137
Mr.Noob
  • 1,005
  • 3
  • 24
  • 58
  • 2
    You are ignoring the value of `dis.read(..)` when writing to `baos`. It returns the actual number of bytes read, now you are always inserting the total length of the buffer. – Mark Rotteveel Mar 05 '13 at 11:51
  • a bit confused mark, can you give me an example please? :) – Mr.Noob Mar 05 '13 at 11:54

1 Answers1

1

You are ignoring that how much number of bytes are actually read.

int numberofBytesRead=dis.read(bBuffer, 0, bBuffer.length);
baos.write(bBuffer, 0, numberOfBytesRead);
kaysush
  • 4,797
  • 3
  • 27
  • 47