Decompress gzip and zlib string in javascript

前端 未结 3 1620
深忆病人
深忆病人 2020-11-27 15:50

I want to get compress layer data from tmx file . Who knows libraries for decompress gzip and zlib string in javascript ? I try zlib but it doesn\'t work for me . Ex , layer

3条回答
  •  臣服心动
    2020-11-27 16:24

    Pako is a full and modern Zlib port.

    Here is a very simple example and you can work from there.

    Get pako.js and you can decompress byteArray like so:

    
    
      Gunzipping binary gzipped string
      
      
    
    
        Open up the developer console.
    
    
    

    Running example: http://jsfiddle.net/9yH7M/

    Alternatively you can base64 encode the array before you send it over as the Array takes up a lot of overhead when sending as JSON or XML. Decode likewise:

    // Get some base64 encoded binary data from the server. Imagine we got this:
    var b64Data     = 'H4sIAAAAAAAAAwXB2w0AEBAEwFbWl2Y0IW4jQmziPNo3k6TuGK0Tj/ESVRs6yzkuHRnGIqPB92qzhg8yp62UMAAAAA==';
    
    // Decode base64 (convert ascii to binary)
    var strData     = atob(b64Data);
    
    // 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:
    var strData     = String.fromCharCode.apply(null, new Uint16Array(data));
    
    // Output to console
    console.log(strData);
    

    Running example: http://jsfiddle.net/9yH7M/1/

    To go more advanced, here is the pako API documentation.

提交回复
热议问题