欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

LZW压缩算法

程序员文章站 2022-03-30 12:21:32
...
PHP实现的LZW压缩算法
  1. /**
  2. * @link http://code.google.com/p/php-lzw/
  3. * @author Jakub Vrana, http://php.vrana.cz/
  4. * @copyright 2009 Jakub Vrana
  5. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
  6. */
  7. /** LZW compression
  8. * @param string data to compress
  9. * @return string binary data
  10. */
  11. function lzw_compress($string) {
  12. // compression
  13. $dictionary = array_flip(range("\0", "\xFF"));
  14. $word = "";
  15. $codes = array();
  16. for ($i=0; $i $x = $string[$i];
  17. if (strlen($x) && isset($dictionary[$word . $x])) {
  18. $word .= $x;
  19. } elseif ($i) {
  20. $codes[] = $dictionary[$word];
  21. $dictionary[$word . $x] = count($dictionary);
  22. $word = $x;
  23. }
  24. }
  25. // convert codes to binary string
  26. $dictionary_count = 256;
  27. $bits = 8; // ceil(log($dictionary_count, 2))
  28. $return = "";
  29. $rest = 0;
  30. $rest_length = 0;
  31. foreach ($codes as $code) {
  32. $rest = ($rest $rest_length += $bits;
  33. $dictionary_count++;
  34. if ($dictionary_count > (1 $bits++;
  35. }
  36. while ($rest_length > 7) {
  37. $rest_length -= 8;
  38. $return .= chr($rest >> $rest_length);
  39. $rest &= (1 }
  40. }
  41. return $return . ($rest_length ? chr($rest }
  42. /** LZW decompression
  43. * @param string compressed binary data
  44. * @return string original data
  45. */
  46. function lzw_decompress($binary) {
  47. // convert binary string to codes
  48. $dictionary_count = 256;
  49. $bits = 8; // ceil(log($dictionary_count, 2))
  50. $codes = array();
  51. $rest = 0;
  52. $rest_length = 0;
  53. for ($i=0; $i $rest = ($rest $rest_length += 8;
  54. if ($rest_length >= $bits) {
  55. $rest_length -= $bits;
  56. $codes[] = $rest >> $rest_length;
  57. $rest &= (1 $dictionary_count++;
  58. if ($dictionary_count > (1 $bits++;
  59. }
  60. }
  61. }
  62. // decompression
  63. $dictionary = range("\0", "\xFF");
  64. $return = "";
  65. foreach ($codes as $i => $code) {
  66. $element = $dictionary[$code];
  67. if (!isset($element)) {
  68. $element = $word . $word[0];
  69. }
  70. $return .= $element;
  71. if ($i) {
  72. $dictionary[] = $word . $element[0];
  73. }
  74. $word = $element;
  75. }
  76. return $return;
  77. }
  78. $data = "";
  79. $compressed = lzw_compress($data);
  80. var_dump($data === lzw_decompress($compressed));
  81. ?>
复制代码
相关标签: LZW压缩算法