1 7 8 package com.sun.imageio.plugins.common; 9 10 import java.io.IOException ; 11 import javax.imageio.stream.ImageOutputStream ; 12 13 18 public class BitFile { 19 ImageOutputStream output; 20 byte buffer[]; 21 int index; 22 int bitsLeft; 24 25 boolean blocks = false; 26 27 31 public BitFile(ImageOutputStream output, boolean blocks) { 32 this.output = output; 33 this.blocks = blocks; 34 buffer = new byte[256]; 35 index = 0; 36 bitsLeft = 8; 37 } 38 39 public void flush() throws IOException { 40 int numBytes = index + (bitsLeft == 8 ? 0 : 1); 41 if (numBytes > 0) { 42 if (blocks) { 43 output.write(numBytes); 44 } 45 output.write(buffer, 0, numBytes); 46 buffer[0] = 0; 47 index = 0; 48 bitsLeft = 8; 49 } 50 } 51 52 public void writeBits(int bits, int numbits) throws IOException { 53 int bitsWritten = 0; 54 int numBytes = 255; do { 56 if ((index == 254 && bitsLeft == 0) || index > 254) { 58 if (blocks) { 59 output.write(numBytes); 60 } 61 62 output.write(buffer, 0, numBytes); 63 64 buffer[0] = 0; 65 index = 0; 66 bitsLeft = 8; 67 } 68 69 if (numbits <= bitsLeft) { if (blocks) { buffer[index] |= (bits & ((1 << numbits) - 1)) << (8 - bitsLeft); 72 bitsWritten += numbits; 73 bitsLeft -= numbits; 74 numbits = 0; 75 } else { 76 buffer[index] |= (bits & ((1 << numbits) - 1)) << (bitsLeft - numbits); 77 bitsWritten += numbits; 78 bitsLeft -= numbits; 79 numbits = 0; 80 } 81 } else { if (blocks) { buffer[index] |= (bits & ((1 << bitsLeft) - 1)) << (8 - bitsLeft); 86 bitsWritten += bitsLeft; 87 bits >>= bitsLeft; 88 numbits -= bitsLeft; 89 buffer[++index] = 0; 90 bitsLeft = 8; 91 } else { 92 int topbits = (bits >>> (numbits - bitsLeft)) & ((1 << bitsLeft) - 1); 96 buffer[index] |= topbits; 97 numbits -= bitsLeft; bitsWritten += bitsLeft; 99 buffer[++index] = 0; bitsLeft = 8; 101 } 102 } 103 } while (numbits != 0); 104 } 105 } 106 | Popular Tags |