1 7 8 package com.sun.imageio.plugins.common; 9 10 import java.io.IOException ; 11 import java.io.PrintStream ; 12 import javax.imageio.stream.ImageOutputStream ; 13 14 18 public class LZWCompressor { 19 20 int codeSize; 21 22 23 int clearCode; 24 25 26 int endOfInfo; 27 28 29 int numBits; 30 31 32 int limit; 33 34 35 short prefix; 36 37 38 BitFile bf; 39 40 41 LZWStringTable lzss; 42 43 44 boolean tiffFudge; 45 46 52 public LZWCompressor(ImageOutputStream out, int codeSize, boolean TIFF) 53 throws IOException 54 { 55 bf = new BitFile(out, !TIFF); this.codeSize = codeSize; 57 tiffFudge = TIFF; 58 clearCode = 1 << codeSize; 59 endOfInfo = clearCode + 1; 60 numBits = codeSize + 1; 61 62 limit = (1 << numBits) - 1; 63 if (tiffFudge) { 64 --limit; 65 } 66 67 prefix = (short)0xFFFF; 68 lzss = new LZWStringTable(); 69 lzss.clearTable(codeSize); 70 bf.writeBits(clearCode, numBits); 71 } 72 73 77 public void compress(byte[] buf, int offset, int length) 78 throws IOException 79 { 80 int idx; 81 byte c; 82 short index; 83 84 int maxOffset = offset + length; 85 for (idx = offset; idx < maxOffset; ++idx) { 86 c = buf[idx]; 87 if ((index = lzss.findCharString(prefix, c)) != -1) { 88 prefix = index; 89 } else { 90 bf.writeBits(prefix, numBits); 91 if (lzss.addCharString(prefix, c) > limit) { 92 if (numBits == 12) { 93 bf.writeBits(clearCode, numBits); 94 lzss.clearTable(codeSize); 95 numBits = codeSize + 1; 96 } else { 97 ++numBits; 98 } 99 100 limit = (1 << numBits) - 1; 101 if (tiffFudge) { 102 --limit; 103 } 104 } 105 prefix = (short)((short)c & 0xFF); 106 } 107 } 108 } 109 110 116 public void flush() throws IOException { 117 if (prefix != -1) { 118 bf.writeBits(prefix, numBits); 119 } 120 121 bf.writeBits(endOfInfo, numBits); 122 bf.flush(); 123 } 124 125 public void dump(PrintStream out) { 126 lzss.dump(out); 127 } 128 } 129 | Popular Tags |