我试图通过捕获 jpeg 图像并将其转换为 base64 字符串来创建视频流,然后使用 websockets(Nodejs 和 socket.io)发送它以在 HTML5 画布上绘图。这是 C# 中用于捕获屏幕并使用SocketIO4Net库发送屏幕的代码:
Client directSocket = new Client("http://IPHERE");
directSocket.Connect();
private void timer1_Tick(object sender, EventArgs e)
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
pictureBox1.Image = bitmap;
// Convert the pictureBox into a byte[] array
System.IO.MemoryStream stream = new System.IO.MemoryStream();
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 string
string base64String = Convert.ToBase64String(imageBytes);
// Send using SocketIO4Net
directSocket.Emit("send", new { message = base64String });
}
这工作正常,base64String 被发送到发出它的节点服务器。这是客户端的javascript代码:
var socket = io.connect('IPHERE');
socket.on('receive', function (data) {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0, canvas.width, canvas.height);
};
img.src = "data:image/jpeg;base64," + data.message.message;
});
我的问题是 base64String 很大,发出的速度不够快,客户端无法接收它并在画布上显示图像。我不确定它是我的节点服务器(它是一个便宜的 VPS)还是字符串太大。是否可以压缩base64String,然后在收到时将其发送解压缩?或者我有其他方法可以做到吗?谢谢您的帮助。