将画布内容序列化为 ArrayBuffer 并再次反序列化

Serialize canvas content to ArrayBuffer and deserialize again(将画布内容序列化为 ArrayBuffer 并再次反序列化)

本文介绍了将画布内容序列化为 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).

这篇关于将画布内容序列化为 ArrayBuffer 并再次反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将画布内容序列化为 ArrayBuffer 并再次反序列化

基础教程推荐