簡體   English   中英

同步將Blob轉換為二進制字符串

[英]Convert Blob to binary string synchronously

當用戶復制畫布選擇時,我正在嘗試將圖像放入剪貼板:

畫布選擇

所以我認為正確的方法是將canvas tu dataURL,dataURL轉換為blob和blob轉換為二進制字符串。

理論上應該可以跳過blob,但我不知道為什么。

所以這就是我做的:

  function copy(event) {
    console.log("copy");
    console.log(event);

    //Get DataTransfer object
    var items = (event.clipboardData || event.originalEvent.clipboardData);
    //Canvas to blob
    var blob = Blob.fromDataURL(_this.editor.selection.getSelectedImage().toDataURL("image/png"));
    //File reader to convert blob to binary string
    var reader = new FileReader();
    //File reader is for some reason asynchronous
    reader.onloadend = function () {
      items.setData(reader.result, "image/png");
    }
    //This starts the conversion
    reader.readAsBinaryString(blob);

    //Prevent default copy operation
    event.preventDefault();
    event.cancelBubble = true;
    return false;
  }
  div.addEventListener('copy', copy);

但是當在paste事件線程之外使用DataTransfer對象時, setData不再有任何生效的機會。

如何在同一個函數線程中進行轉換?

這是一種從blob到它的字節同步的hacky-way。 我不確定它對任何二進制數據的效果如何。

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]

你應該考慮讓它保持異步但是讓它成為兩個階段,因為你最終可能會鎖定瀏覽器。

此外,您可以通過包含二進制安全的Base64解碼器完全跳過Blob ,您可能不需要通過Base64 AND Blob ,只需其中一個。

通過將Blob作為d ataURI然后應用atob可以將Blob轉換為二進制字符串。 然而,這又[需要FileReader][3] 在我的情況下,最好完全跳過blob:

//Canvas to binary
var data = atob(
  _this.editor.selection.getSelectedImage()  //Canvas
  .toDataURL("image/png")                    //Base64 URI
  .split(',')[1]                             //Base64 code
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM