LZW compression algorithm
LZW compression algorithm implemented by PHP
- /**
- * @ Link http://code.google.com/p/php-lzw/
- * @ Author Jakub Vrana, http://php.vrana.cz/
- * @ Copyright 2009 Jakub Vrana
- * @ License http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
- */
- /** LZW compression
- * @ Param string data to compress
- * @ Return string binary data
- */
- Function lzw_compress ($ string ){
- // Compression
- $ Dictionary = array_flip (range ("\ 0", "\ xFF "));
- $ Word = "";
- $ Codes = array ();
- For ($ I = 0; $ I <= strlen ($ string); $ I ++ ){
- $ X = $ string [$ I];
- If (strlen ($ x) & isset ($ dictionary [$ word. $ x]) {
- $ Word. = $ x;
- } Elseif ($ I ){
- $ Codes [] = $ dictionary [$ word];
- $ Dictionary [$ word. $ x] = count ($ dictionary );
- $ Word = $ x;
- }
- }
- // Convert codes to binary string
- $ Dictionary_count = 256;
- $ Bits = 8; // ceil (log ($ dictionary_count, 2 ))
- $ Return = "";
- $ Rest = 0;
- $ Rest_length = 0;
- Foreach ($ codes as $ code ){
- $ Rest = ($ rest <$ bits) + $ code;
- $ Rest_length + = $ bits;
- $ Dictionary_count ++;
- If ($ dictionary_count> (1 <$ bits )){
- $ Bits ++;
- }
- While ($ rest_length> 7 ){
- $ Rest_length-= 8;
- $ Return. = chr ($ rest >>$ rest_length );
- $ Rest & = (1 <$ rest_length)-1;
- }
- }
- Return $ return. ($ rest_length? Chr ($ rest <(8-$ rest_length )):"");
- }
- /** LZW decompression
- * @ Param string compressed binary data
- * @ Return string original data
- */
- Function lzw_decompress ($ binary ){
- // Convert binary string to codes
- $ Dictionary_count = 256;
- $ Bits = 8; // ceil (log ($ dictionary_count, 2 ))
- $ Codes = array ();
- $ Rest = 0;
- $ Rest_length = 0;
- For ($ I = 0; $ I <strlen ($ binary); $ I ++ ){
- $ Rest = ($ rest <8) + ord ($ binary [$ I]);
- $ Rest_length + = 8;
- If ($ rest_length >=$ bits ){
- $ Rest_length-= $ bits;
- $ Codes [] = $ rest >$ rest_length;
- $ Rest & = (1 <$ rest_length)-1;
- $ Dictionary_count ++;
- If ($ dictionary_count> (1 <$ bits )){
- $ Bits ++;
- }
- }
- }
- // Decompression
- $ Dictionary = range ("\ 0", "\ xFF ");
- $ Return = "";
- Foreach ($ codes as $ I =>$ code ){
- $ Element = $ dictionary [$ code];
- If (! Isset ($ element )){
- $ Element = $ word. $ word [0];
- }
- $ Return. = $ element;
- If ($ I ){
- $ Dictionary [] = $ word. $ element [0];
- }
- $ Word = $ element;
- }
- Return $ return;
- }
- $ Data = "";
- $ Compressed = lzw_compress ($ data );
- Var_dump ($ data === lzw_decompress ($ compressed ));
- ?>
|