ホームページ  >  記事  >  バックエンド開発  >  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 ライセンス、バージョン 2.0
  6. */
  7. /**LZW 圧縮
  8. * @param 圧縮する文字列データ
  9. * @return 文字列バイナリデータ
  10. */
  11. function lzw_compress($string) {
  12. // 圧縮
  13. $dictionary = array_flip(range(" ", "xFF"));
  14. $word = "";
  15. $codes = array();
  16. for ($i=0; $i <= strlen($string); $i++) {
  17. $x = $string [$i];
  18. if (strlen($x) && isset($dictionary[$word . $x])) {
  19. $word .= $x;
  20. } elseif ($i) {
  21. $codes[] = $dictionary[$word];
  22. $dictionary[$word . $x] = count($dictionary);
  23. $word = $x;
  24. }
  25. }
  26. // コードをバイナリ文字列に変換します
  27. $dictionary_count = 256;
  28. $bits = 8; // ceil(log($dictionary_count, 2))
  29. $return = "";
  30. $rest = 0;
  31. $rest_length = 0;
  32. foreach ($codes as $code) {
  33. $rest = ($rest < < $bits) + $code;
  34. $rest_length += $bits;
  35. $dictionary_count++;
  36. if ($dictionary_count > (1 << $bits)) {
  37. $bits++;
  38. }
  39. while ($rest_length > 7) {
  40. $rest_length -= 8;
  41. $return .= chr($rest >> $rest_length);
  42. $rest &= (1 << $rest_length) - 1;
  43. }
  44. }
  45. $return を返します。 ($rest_length ? chr($rest << (8 - $rest_length)) : "");
  46. }
  47. /**LZW解凍
  48. * @param文字列圧縮バイナリデータ
  49. * @return文字列元データ
  50. */
  51. function lzw_decompress($binary) {
  52. // バイナリ文字列を変換コードへ
  53. $dictionary_count = 256;
  54. $bits = 8; // ceil(log($dictionary_count, 2))
  55. $codes = array();
  56. $rest = 0;
  57. $rest_length = 0;
  58. for ($i=0; $i $rest = ($rest << 8) + ord($binary[$i]);
  59. $rest_length += 8;
  60. if ($rest_length >= $bits) {
  61. $rest_length -= $bits;
  62. $codes[] = $rest >> $rest_length;
  63. $rest &= (1 << $rest_length) - 1;
  64. $dictionary_count++;
  65. if ($dictionary_count > (1 << $bits)) {
  66. $bits++;
  67. }
  68. }
  69. }
  70. // 解凍
  71. $dictionary = range(" ", "xFF");
  72. $return = "";
  73. foreach ($codes as $i => $code) {
  74. $element = $dictionary[ $code];
  75. if (!isset($element)) {
  76. $element = $word . $word[0];
  77. }
  78. $return .= $element;
  79. if ($i) {
  80. $dictionary[] = $word . $element[0];
  81. }
  82. $word = $element;
  83. }
  84. return $return;
  85. }
  86. $data = "";
  87. $compressed = lzw_compress($data);
  88. var_dump($data === lzw_decompress ($compressed));
  89. ?>
复制發


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:シンプルな電卓次の記事:シンプルな電卓