private Mat streamToMat ( InputStream is ) throws IOException { if ( buffer == null ) { buffer = IOUtils . toByteArray ( is ) ; bufferMat = new Mat ( buffer ) ; return bufferMat ; } else { int numReadTotal = is . read ( buffer ) ; //Need to know if all data has been read. //(a) if numRead < buffer.length - got everything //(b) if numRead >= buffer.length: we MIGHT have got everything (exact right size buffer) OR we need more data if ( numReadTotal < buffer . length ) { bufferMat . data ( ) . put ( buffer , 0 , numReadTotal ) ; bufferMat . cols ( numReadTotal ) ; return bufferMat ; } //Buffer is full; reallocate and keep reading int numReadCurrent = numReadTotal ; while ( numReadCurrent != - 1 ) { byte [ ] oldBuffer = buffer ; if ( oldBuffer . length == Integer . MAX_VALUE ) { throw new IllegalStateException ( "Cannot read more than Integer.MAX_VALUE bytes" ) ; } //Double buffer, but allocate at least 1MB more long increase = Math . max ( buffer . length , MIN_BUFFER_STEP_SIZE ) ; int newBufferLength = ( int ) Math . min ( Integer . MAX_VALUE , buffer . length + increase ) ; buffer = new byte [ newBufferLength ] ; System . arraycopy ( oldBuffer , 0 , buffer , 0 , oldBuffer . length ) ; numReadCurrent = is . read ( buffer , oldBuffer . length , buffer . length - oldBuffer . length ) ; if ( numReadCurrent > 0 ) { numReadTotal += numReadCurrent ; } } bufferMat = new Mat ( buffer ) ; return bufferMat ; } }
Read the stream to the buffer and return the number of bytes read