blob pb 转二进制_同步将Blob转换为二进制字符串

本文档介绍如何将canvas选择转换为clipboard的二进制图像。首先,将canvas转换为dataURL,然后将dataURL转换为blob,最后将blob转换为二进制字符串。尽管可以直接从dataURL操作,但作者遇到了问题。提供的代码示例展示了一个不成功的方法,由于文件读取器的异步性质,导致setData无法生效。提出了一个同步转换blob到Uint8Array的hack方法,但也警告这可能使浏览器挂起,并建议保持异步处理。
摘要由CSDN通过智能技术生成

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

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

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

So this is what I did:

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

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?

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值