Convert Blob to binary string synchronously

前端 未结 2 1414
刺人心
刺人心 2020-12-21 02:45

I\'m trying to put image in clipboard when user copies canvas selection:

\"canvas

So I thou

相关标签:
2条回答
  • 2020-12-21 03:39

    Here is a hacky-way to get you synchronously from a blob to it's bytes. I'm not sure how well this works for any binary data.

    function blobToUint8Array(b) {
        var uri = URL.createObjectURL(b),
            xhr = new XMLHttpRequest(),
            i,
            ui8;
    
        xhr.open('GET', uri, false);
        xhr.send();
    
        URL.revokeObjectURL(uri);
    
        ui8 = new Uint8Array(xhr.response.length);
    
        for (i = 0; i < xhr.response.length; ++i) {
            ui8[i] = xhr.response.charCodeAt(i);
        }
    
        return ui8;
    }
    
    var b = new Blob(['abc'], {type: 'application/octet-stream'});
    blobToUint8Array(b); // [97, 98, 99]
    

    You should consider keeping it async but making it two-stage, though, as you may end up locking up the browser.

    Additionally, you can skip Blobs entirely by including a binary-safe Base64 decoder, and you probably don't need to go via Base64 AND Blob, just one of them.

    0 讨论(0)
  • 2020-12-21 03:43

    Blob can be converted to binary string by getting Blob as dataURI and then applying atob. This, however, again [requires FileReader][3]. In my case, it's best to skip the blob alltogether:

    //Canvas to binary
    var data = atob(
      _this.editor.selection.getSelectedImage()  //Canvas
      .toDataURL("image/png")                    //Base64 URI
      .split(',')[1]                             //Base64 code
    );
    
    0 讨论(0)
提交回复
热议问题