将画布内容序列化为 ArrayBuffer 并再次反序列化
我有两个画布,我想把canvas1的内容传过来,序列化到一个ArrayBuffer中,然后加载到canvas2中.以后我会把canvas1的内容发送到服务器,处理后返回给canvas2,但是现在只想序列化和反序列化.
I have two canvases, and I want to pass the content of canvas1, serialize it to an ArrayBuffer, and then load it in canvas2. In the future I will send the canvas1 content to the server, process it, and return it to canvas2, but right now I just want to serialize and deserialize it.
我发现了这种以字节为单位获取画布信息的方法:
I found this way of getting the canvas info in bytes:
var img1 = context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img1.data.length);
for (var i = 0; i < img1.data.length; i++) {
binary[i] = img1.data[i];
}
还发现了这种将信息设置为Image
对象的方法:
And also found this way of set the information to a Image
object:
var blob = new Blob( [binary], { type: "image/png" } );
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
var img = new Image();
img.src = imageUrl;
但不幸的是,它似乎不起作用.
But unfortunately it doesn't seem to work.
这样做的正确方法是什么?
Which would be the right way of doing this?
推荐答案
您从 getImageData()
获得的 ImageData 已经在使用 ArrayBuffer(由 Uint8ClampedArray
视图使用).抓住它并发送它:
The ImageData you get from getImageData()
is already using an ArrayBuffer (used by the Uint8ClampedArray
view). Just grab it and send it:
var imageData = context.getImageData(x, y, w, h);
var buffer = imageData.data.buffer; // ArrayBuffer
重新设置:
var imageData = context.createImageData(w, h);
imageData.data.set(incomingBuffer);
您可能想要考虑某种形式的字节编码(例如 f.ex base-64),因为任何高于 127 (ASCII) 的字节值都受系统上使用的字符编码的影响.或者确保旅途中的所有步骤都使用相同的(例如 UTF8).
You probably want to consider some form of byte encoding though (such as f.ex base-64) as any byte value above 127 (ASCII) is subject to character encoding used on a system. Or make sure all steps on the trip uses the same (f.ex. UTF8).
相关文章