Converting bytes to an image for drawing on a HTML5 canvas(将字节转换为图像以在 HTML5 画布上绘图)
问题描述
有人知道我如何将通过 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 画布上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将字节转换为图像以在 HTML5 画布上绘图


基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01