@Override
public final DecodeResult decode(InputStream encoded, OutputStream decoded,
COSDictionary parameters, int index) throws IOException
{
ImageReader reader = findImageReader("JBIG2", "jbig2-imageio is not installed");
DecodeResult result = new DecodeResult(new COSDictionary());
result.getParameters().addAll(parameters);
COSInteger bits = (COSInteger) parameters.getDictionaryObject(COSName.BITS_PER_COMPONENT);
COSDictionary params = (COSDictionary) parameters.getDictionaryObject(COSName.DECODE_PARMS);
COSStream globals = null;
if (params != null)
{
globals = (COSStream) params.getDictionaryObject(COSName.JBIG2_GLOBALS);
}
ImageInputStream iis = null;
try
{
if (globals != null)
{
iis = ImageIO.createImageInputStream(
new SequenceInputStream(globals.getUnfilteredStream(), encoded));
reader.setInput(iis);
}
else
{
iis = ImageIO.createImageInputStream(encoded);
reader.setInput(iis);
}
BufferedImage image;
try
{
image = reader.read(0);
}
catch (Exception e)
{
// wrap and rethrow any exceptions
throw new IOException("Could not read JBIG2 image", e);
}
// I am assuming since JBIG2 is always black and white
// depending on your renderer this might or might be needed
if (image.getColorModel().getPixelSize() != bits.intValue())
{
if (bits.intValue() != 1)
{
LOG.warn("Attempting to handle a JBIG2 with more than 1-bit depth");
}
BufferedImage packedImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_BYTE_BINARY);
Graphics graphics = packedImage.getGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
image = packedImage;
}
DataBuffer dBuf = image.getData().getDataBuffer();
if (dBuf.getDataType() == DataBuffer.TYPE_BYTE)
{
decoded.write(((DataBufferByte) dBuf).getData());
}
else
{
throw new IOException("Unexpected image buffer type");
}
}
finally
{
if (iis != null)
{
iis.close();
}
reader.dispose();
}
// repair missing color space
if (!parameters.containsKey(COSName.COLORSPACE))
{