Monday, April 6, 2015

JavaScript ZLIB Decompression

Download Pako: https://github.com/nodeca/pako

<html>
<head>
  <script src="pako-master/dist/pako.min.js"></script>
</head>
<body>

<?php
  $str = 'Hello, World!';
  $strGZCompressedBase64Encoded = base64_encode(gzcompress($str));
?>

<script>
  var strGZCompressedBase64Encoded = '<?php echo $strGZCompressedBase64Encoded; ?>';
  var str = uncompress_base64decode(strGZCompressedBase64Encoded);
  console.log(str);

  function uncompress_base64decode(strGZCompressedBase64Encoded) {
    // Decode base64 (convert ascii to binary)
    var strData = atob(strGZCompressedBase64Encoded);

    // Convert binary string to character-number array
    var charData = strData.split('').map(function(x){return x.charCodeAt(0);});

    // Turn number array into byte-array
    var binData = new Uint8Array(charData);

    // Pako magic
    var data = pako.inflate(binData);

    // Convert gunzipped byteArray back to ascii string:
    return String.fromCharCode.apply(null, new Uint16Array(data));
  }
</script>

</body>
</html>

Reference:

http://stackoverflow.com/questions/4507316/zlib-decompression-client-side
http://stackoverflow.com/questions/14620769/decompress-gzip-and-zlib-string-in-javascript

No comments: