>  기사  >  백엔드 개발  >  LZW压缩算法

LZW压缩算法

WBOY
WBOY원래의
2016-07-25 09:07:591530검색
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. ?>
复制代码


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:简单、计算器 다음 기사:博大精深的 农历算法