public void decode(InputStream compressedData,
OutputStream result,
COSDictionary options,
int filterIndex) throws IOException {
COSBase baseObj = options.getDictionaryObject(new String[] {"DecodeParms","DP"});
COSDictionary dict = null;
if( baseObj instanceof COSDictionary )
{
dict = (COSDictionary)baseObj;
}
else if( baseObj instanceof COSArray )
{
COSArray paramArray = (COSArray)baseObj;
if( filterIndex < paramArray.size() )
{
dict = (COSDictionary)paramArray.getObject( filterIndex );
}
}
else if( baseObj == null )
{
//do nothing
}
else
{
throw new IOException( "Error: Expected COSArray or COSDictionary and not "
+ baseObj.getClass().getName() );
}
int predictor = -1;
int colors = -1;
int bitsPerPixel = -1;
int columns = -1;
InflaterInputStream decompressor = null;
ByteArrayInputStream bais = null;
ByteArrayOutputStream baos = null;
if (dict!=null)
{
predictor = dict.getInt("Predictor");
if(predictor > 1)
{
colors = dict.getInt("Colors");
bitsPerPixel = options.getInt("BitsPerComponent");
columns = dict.getInt("Columns");
}
}
try
{
// Decompress data to temporary ByteArrayOutputStream
decompressor = new InflaterInputStream(compressedData);
int amountRead;
int mayRead = compressedData.available();
if (mayRead > 0)
{
byte[] buffer = new byte[Math.min(mayRead,BUFFER_SIZE)];
// Decode data using given predictor
if (predictor==-1 || predictor == 1 || predictor == 10)
{
try
{
// decoding not needed
while ((amountRead = decompressor.read(buffer, 0, Math.min(mayRead,BUFFER_SIZE))) != -1)
{
result.write(buffer, 0, amountRead);
}
}
catch (OutOfMemoryError exception)
{
// if the stream is corrupt an OutOfMemoryError may occur
log.error("Stop reading corrupt stream");
}
catch (ZipException exception)
{
// if the stream is corrupt an OutOfMemoryError may occur
log.error("Stop reading corrupt stream");
}
catch (EOFException exception)
{
// if the stream is corrupt an OutOfMemoryError may occur
log.error("Stop reading corrupt stream");
}
}
else
{
/*
* Reverting back to default values
*/
if( colors == -1 )
{
colors = 1;
}
if( bitsPerPixel == -1 )
{
bitsPerPixel = 8;
}
if( columns == -1 )
{
columns = 1;
}
baos = new ByteArrayOutputStream();
while ((amountRead = decompressor.read(buffer, 0, Math.min(mayRead,BUFFER_SIZE))) != -1)
{
baos.write(buffer, 0, amountRead);
}
baos.flush();
// Copy data to ByteArrayInputStream for reading
bais = new ByteArrayInputStream(baos.toByteArray());
baos.close();
baos = null;
byte[] decodedData = decodePredictor(predictor, colors, bitsPerPixel, columns, bais);
bais.close();
bais = new ByteArrayInputStream(decodedData);
// write decoded data to result
while ((amountRead = bais.read(buffer)) != -1)
{
result.write(buffer, 0, amountRead);
}
bais.close();
bais = null;
}
}
result.flush();
}
finally
{
if (decompressor != null)
{
decompressor.close();
}
if (bais != null)
{
bais.close();
}
if (baos != null)
{
baos.close();
}
}
}
|