简体   繁体   English

将字节转换为图像以在HTML5画布上绘制

[英]Converting bytes to an image for drawing on a HTML5 canvas

Anyone know how I would convert bytes which are sent via a websocket (from a C# app) to an image? 任何人都知道如何转换通过websocket(从C#应用程序)发送到图像的字节? I then want to draw the image on a canvas. 然后我想在画布上绘制图像。 I can see two ways of doing this: 我可以看到两种方法:

  • Somehow draw the image on the canvas in byte form without converting it. 以某种方式在画布上以字节形式绘制图像而不转换它。
  • Convert the bytes to a base64 string somehow in javascript then draw. 在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;

}

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. 我之前收到的图像已经转换为base64字符串了,但是在得知发送字节的尺寸较小(小30%?)后,我宁愿让它工作。 I should also mention that the image is a jpeg. 我还应该提到图像是一个jpeg。

Anyone know how I would do it? 谁知道我会怎么做? Thanks for the help. 谢谢您的帮助。 :) :)

If your image is really a jpeg already, you can just convert the received data to a base64 stream. 如果您的图像已经是jpeg,则可以将接收的数据转换为base64流。 Firefox and Webkit browsers (as I recall) have a certain function, btoa() . Firefox和Webkit浏览器(我记得)有一定的功能, btoa() It converts the input string to a base64 encoded string. 它将输入字符串转换为base64编码的字符串。 Its counterpart is atob() that does the opposite. 它的对应物是atob() ,它正好相反。

You could use it like the following: 您可以像下面这样使用它:

function draw(imgData){
    var b64imgData = btoa(imgData); //Binary to ASCII, where it probably stands for
    var img = new Image();
    img.src = "data:image/jpeg;base64," + b64imgData;
    document.body.appendChild(img); //or append it to something else, just an example
}

If the browser you target (IE, for example) isn't Firefox or a Webkit one, you can use one of the multiple conversion function lying around the internet ( good one , it also provides statistics of performances in multiple browsers, if you're interested :) 如果您定位的浏览器(例如IE)不是Firefox或Webkit,您可以使用互联网周围的多重转换功能之一好的 ,它还提供多个浏览器的性能统计,如果你'有兴趣:)

I used this in the end: 我最后用这个:

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

I needed to read the bytes into a string before using btoa(). 在使用btoa()之前,我需要将字节读入字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM