123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187 |
- <?php
- namespace Fpdi\PdfParser\Filter;
- class Lzw implements FilterInterface
- {
-
- protected $data;
-
- protected $sTable = [];
-
- protected $dataLength = 0;
-
- protected $tIdx;
-
- protected $bitsToGet = 9;
-
- protected $bytePointer;
-
- protected $nextData = 0;
-
- protected $nextBits = 0;
-
- protected $andTable = [511, 1023, 2047, 4095];
-
- public function decode($data)
- {
- if ($data[0] === "\x00" && $data[1] === "\x01") {
- throw new LzwException(
- 'LZW flavour not supported.',
- LzwException::LZW_FLAVOUR_NOT_SUPPORTED
- );
- }
- $this->initsTable();
- $this->data = $data;
- $this->dataLength = \strlen($data);
-
- $this->bytePointer = 0;
- $this->nextData = 0;
- $this->nextBits = 0;
- $oldCode = 0;
- $uncompData = '';
- while (($code = $this->getNextCode()) !== 257) {
- if ($code === 256) {
- $this->initsTable();
- $code = $this->getNextCode();
- if ($code === 257) {
- break;
- }
- $uncompData .= $this->sTable[$code];
- $oldCode = $code;
- } else {
- if ($code < $this->tIdx) {
- $string = $this->sTable[$code];
- $uncompData .= $string;
- $this->addStringToTable($this->sTable[$oldCode], $string[0]);
- $oldCode = $code;
- } else {
- $string = $this->sTable[$oldCode];
- $string .= $string[0];
- $uncompData .= $string;
- $this->addStringToTable($string);
- $oldCode = $code;
- }
- }
- }
- return $uncompData;
- }
-
- protected function initsTable()
- {
- $this->sTable = [];
- for ($i = 0; $i < 256; $i++) {
- $this->sTable[$i] = \chr($i);
- }
- $this->tIdx = 258;
- $this->bitsToGet = 9;
- }
-
- protected function addStringToTable($oldString, $newString = '')
- {
- $string = $oldString . $newString;
-
- $this->sTable[$this->tIdx++] = $string;
- if ($this->tIdx === 511) {
- $this->bitsToGet = 10;
- } elseif ($this->tIdx === 1023) {
- $this->bitsToGet = 11;
- } elseif ($this->tIdx === 2047) {
- $this->bitsToGet = 12;
- }
- }
-
- protected function getNextCode()
- {
- if ($this->bytePointer === $this->dataLength) {
- return 257;
- }
- $this->nextData = ($this->nextData << 8) | (\ord($this->data[$this->bytePointer++]) & 0xff);
- $this->nextBits += 8;
- if ($this->nextBits < $this->bitsToGet) {
- $this->nextData = ($this->nextData << 8) | (\ord($this->data[$this->bytePointer++]) & 0xff);
- $this->nextBits += 8;
- }
- $code = ($this->nextData >> ($this->nextBits - $this->bitsToGet)) & $this->andTable[$this->bitsToGet - 9];
- $this->nextBits -= $this->bitsToGet;
- return $code;
- }
- }
|