List of usage examples for javax.imageio.stream MemoryCacheImageOutputStream writeBits
public void writeBits(long bits, int numBits) throws IOException
From source file:org.apache.pdfbox.filter.LZWFilter.java
/** * {@inheritDoc}//from ww w .jav a 2 s.c om */ @Override protected void encode(InputStream rawData, OutputStream encoded, COSDictionary parameters) throws IOException { List<byte[]> codeTable = createCodeTable(); int chunk = 9; byte[] inputPattern = null; final MemoryCacheImageOutputStream out = new MemoryCacheImageOutputStream(encoded); out.writeBits(CLEAR_TABLE, chunk); int foundCode = -1; int r; while ((r = rawData.read()) != -1) { byte by = (byte) r; if (inputPattern == null) { inputPattern = new byte[] { by }; foundCode = by & 0xff; } else { inputPattern = Arrays.copyOf(inputPattern, inputPattern.length + 1); inputPattern[inputPattern.length - 1] = by; int newFoundCode = findPatternCode(codeTable, inputPattern); if (newFoundCode == -1) { // use previous chunk = calculateChunk(codeTable.size() - 1, 1); out.writeBits(foundCode, chunk); // create new table entry codeTable.add(inputPattern); if (codeTable.size() == 4096) { // code table is full out.writeBits(CLEAR_TABLE, chunk); codeTable = createCodeTable(); } inputPattern = new byte[] { by }; foundCode = by & 0xff; } else { foundCode = newFoundCode; } } } if (foundCode != -1) { chunk = calculateChunk(codeTable.size() - 1, 1); out.writeBits(foundCode, chunk); } // PPDFBOX-1977: the decoder wouldn't know that the encoder would output // an EOD as code, so he would have increased his own code table and // possibly adjusted the chunk. Therefore, the encoder must behave as // if the code table had just grown and thus it must be checked it is // needed to adjust the chunk, based on an increased table size parameter chunk = calculateChunk(codeTable.size(), 1); out.writeBits(EOD, chunk); // pad with 0 out.writeBits(0, 7); // must do or file will be empty :-( out.flush(); out.close(); }