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 画布上绘图
基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01