Frage

I'm using a websocket to send a Jpeg image in blob form. I've compressed (gzipped) the blob but I'm unable to find a way to decompress it using JavaScript. Does anyone know how?

This is the code I'm using to read the blob and then convert it into a base64 string:

var r = new FileReader();

r.onload = function(){
    draw(btoa(r.result));
};
r.readAsBinaryString(e.data);

The draw() function basically draws the image using the base64 string, onto a HTML5 canvas.

I've found this library to inflate strings, but it doesn't support blobs. (As far as I know / have tested) If anyone knows of a way, I would appriciate it. :) Thanks!

War es hilfreich?

Lösung

I've done a very similar thing for my particle system editor, it has support for reading Cocos2D plist files. In the plist file is texture data, which is a png that has been compressed with gzip and then converted to base64. Here is how I do it:

var input = 'byu9g1RZpINUpVtoKoiKIqJYoris...'; // really long string

// from base64 to ascii binary string
var decodedAsString = atob(input);

// ascii string to bytes in gzipped format
var data = this._binaryStringToArray(decodedAsString);

// raw, uncompressed, binary image data into an array using gzip.js
var uncompressed = require('gzip-js').unzip(data);

// now take the raw uncompressed png and convert it
// back to base64 to use it as a data url
var asString = this._arrayToBinaryString(uncompressed);
var encodedForDataUrl = btoa(asString);

var img = new Image();
img.src = encodedForDataUrl;

I am using gzip.js to do the heavy lifting. You can see all this in action here, you can get some plists to load into it here. BoilingFoam.plist will work, just load it in the "Import/Export" section.

In the above code I call two methods, here they are:

 _binaryStringToArray: function(binaryString) {
        var data = [];

        for (var i = 0; i < binaryString.length; ++i) {
            data[i] = binaryString.charCodeAt(i);
        }

        return data;
    },

    _arrayToBinaryString: function(array) {
        var str = '';
        for (var i = 0; i < array.length; ++i) {
            str += String.fromCharCode(array[i]);
        }
        return str;
    },

The whole shebang is here

Andere Tipps

Get a byteArray and you can decode it using pako: http://jsfiddle.net/9yH7M/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top