问题描述
有人知道我如何将通过 websocket(从 C# 应用程序)发送的字节转换为图像吗?然后我想在画布上绘制图像.我可以看到两种方法:
Anyone know how I would convert bytes which are sent via a websocket (from a C# app) to an image? I then want to draw the image on a canvas. I can see two ways of doing this:
- 不知何故以字节形式在画布上绘制图像而不转换它.
- 然后在javascript中以某种方式将字节转换为base64字符串画.
这是我接收绘图字节的函数:
Here's my function which receives the bytes for drawing:
function draw(imgData) {
var img=new Image();
img.onload = function() {
cxt.drawImage(img, 0, 0, canvas.width, canvas.height);
};
// What I was using before...
img.src = "data:image/jpeg;base64,"+imgData;
}
我之前收到的图像已经转换为 base64 字符串,但在得知发送字节的大小更小(小 30%?)之后,我更愿意让它工作.我还应该提到图像是 jpeg.
I was receiving the image already converted as a base64 string before, but after learning that sending the bytes is smaller in size (30% smaller?) I would prefer to get this working. I should also mention that the image is a jpeg.
有人知道我会怎么做吗?谢谢您的帮助.:)
Anyone know how I would do it? Thanks for the help. :)
推荐答案
我最后用了这个:
function draw(imgData, frameCount) {
var r = new FileReader();
r.readAsBinaryString(imgData);
r.onload = function(){
var img=new Image();
img.onload = function() {
cxt.drawImage(img, 0, 0, canvas.width, canvas.height);
}
img.src = "data:image/jpeg;base64,"+window.btoa(r.result);
};
}
在使用 btoa() 之前,我需要将字节读入字符串.
I needed to read the bytes into a string before using btoa().
这篇关于将字节转换为图像以在 HTML5 画布上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!