将jpeg数组直接绘制到Canvas上

时间:2022-10-01 21:22:04

At the moment I get a byte array of a JPEG from my signalr connection and load it into a image and on the image.onload event I draw the image to my canvas.

目前,我从信号器连接中获取了一个JPEG字节数组,并将其加载到图像中,在image.onload事件中,我将图像绘制到画布上。

so:

desktopImage.onload = function () {
    myCanvasContext.drawImage(desktopImage, 0, 0);
}

chat.client.broadcastMessage = function (jpeg) {
    desktopImage.src = 'data:image/jpeg;base64,' + jpeg;
}

Which does work well.

哪个效果很好。

I was wondering whether i could 'quicken' this process by drawing the image directly onto the canvas without 1st loading it to an image 1st.

我想知道我是否可以通过直接将图像绘制到画布上来“加快”这个过程,而不是先将图像加载到图像上。

Is it possible?

可能吗?

1 个解决方案

#1


If you receive a byte array as you state, assuming ArrayBuffer, you could wrap it as a Blob object and create an object URL for it instead. This will save significant overhead from encoding and decoding Base-64:

如果您在声明时收到字节数组,假设使用ArrayBuffer,则可以将其包装为Blob对象并为其创建对象URL。这将节省编码和解码Base-64的大量开销:

Example:

var desktopImage = new Image();
var url;

desktopImage.onload = function () {
    myCanvasContext.drawImage(desktopImage, 0, 0);
    (URL || webkitURL).revokeObjectURL(url);  // release memory
}

// assuming jpeg = ArrayBuffer:
chat.client.broadcastMessage = function (jpeg) {
    var blob = new Blob([jpeg], {type: "image/jpeg"});
    url = (URL || webkitURL).createObjectURL(blob);

    desktopImage.src = url;
}

#1


If you receive a byte array as you state, assuming ArrayBuffer, you could wrap it as a Blob object and create an object URL for it instead. This will save significant overhead from encoding and decoding Base-64:

如果您在声明时收到字节数组,假设使用ArrayBuffer,则可以将其包装为Blob对象并为其创建对象URL。这将节省编码和解码Base-64的大量开销:

Example:

var desktopImage = new Image();
var url;

desktopImage.onload = function () {
    myCanvasContext.drawImage(desktopImage, 0, 0);
    (URL || webkitURL).revokeObjectURL(url);  // release memory
}

// assuming jpeg = ArrayBuffer:
chat.client.broadcastMessage = function (jpeg) {
    var blob = new Blob([jpeg], {type: "image/jpeg"});
    url = (URL || webkitURL).createObjectURL(blob);

    desktopImage.src = url;
}