同步将Blob转换为二进制字符串 [英] Convert Blob to binary string synchronously

查看:1256
本文介绍了同步将Blob转换为二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户复制画布选择时,我正在尝试将图像放入剪贴板:

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

所以我认为正确的方法是将canvas tu dataURL,dataURL转换为blob和blob为二进制字符串。

So I thought the right way would be to convert canvas tu dataURL, dataURL to blob and blob to binary string.

从理论上讲,应该可以跳过blob,但我不知道为什么。

Theoretically it should be possible to skip the blob, but I don't know why.

所以这是我做了什么:

  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);

但是当 DataTransfer 对象用完时粘贴事件线程 setData 已不再生效。

But when the DataTransfer object is used out of the paste event thread the setData has no longer any chance to take effect.

如何在同一个函数线程中进行转换?

How can I do the conversion in the same function thread?

推荐答案

这是一个hacky-way让你从blob同步到它的字节。我不确定它对任何二进制数据的效果如何。

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.

此外,您可以通过包含二进制安全来完全跳过 Blobs > Base64 解码器,您可能不需要通过 Base64 AND Blob ,只需其中一个。

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.

这篇关于同步将Blob转换为二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆