2019独角兽企业重金招聘Python工程师标准>>>
通过WebSocket链接,网页和服务端可以实现异步双向通讯。这里介绍如何从服务端获取一张图片,然后传输到网页中显示出来。
参考原文:
Image Transmission between a HTML5 WebSocket Server and a Web Client
准备工作
下载SuperWebSocket
下载Dynamic .NET TWAIN
阅读 Program.cs和Test.htm
创建WebSocket Server
创建一个WinForms工程,导入需要的reference。
添加namespace:
using Dynamsoft.DotNet.TWAIN;
using SuperSocket.SocketBase;
using SuperWebSocket;
建立Server:
if (!appServer.Setup("192.168.8.84", 2012)) //Setup with listening port
{
MessageBox.Show("Failed to setup!");
return;
}
加载一张图片:
bool isLoad = dynamicDotNetTwain.LoadImage("dynamsoft_logo_black.png"); // load an image
Image img = dynamicDotNetTwain.GetImage(0);
把数据转换成bmp格式:
byte[] result;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); // convert png to bmp
result = stream.GetBuffer();
}
获得实际数据的长度:
int iRealLen = result.Length - 54;
byte[] image = new byte[iRealLen];
为了让数据能够在网页中正常显示,需要对数据进行处理。数据需要从尾到头读取,不然显示的数据是颠倒的。蓝色和红色的位置需要交换一下,不然颜色是错误的:
int iIndex = 0;
int iRowIndex = 0;
int iWidth = width * 4;
for (int i = height - 1; i >= 0; --i)
{
iRowIndex = i * iWidth;
for (int j = 0; j < iWidth; j += 4)
{
// RGB to BGR
image[iIndex++] = result[iRowIndex + j + 2 + 54]; // B
image[iIndex++] = result[iRowIndex + j + 1 + 54]; // G
image[iIndex++] = result[iRowIndex + j + 54]; // R
image[iIndex++] = result[iRowIndex + j + 3 + 54]; // A
}
}
现在发送数据:
session.Send(imageData.Data, 0, imageData.Data.Length);
创建Web客户端
在Web端使用JavaScript创建WebSocket之后,需要设置属性:
ws.binaryType =
"arraybuffer"
;
收到ArrayBuffer之后,创建image元素,把图像画出来:
var imageWidth = 73, imageHeight = 73; // hardcoded width & height.
var byteArray = new Uint8Array(data);
var canvas = document.createElement('canvas');
canvas.height = imageWidth;
canvas.width = imageHeight;
var ctx = canvas.getContext('2d');
var imageData = ctx.getImageData(0, 0, imageWidth, imageHeight); // total size: imageWidth * imageHeight * 4; color format BGRA
var dataLen = imageData.data.length;
for (var i = 0; i < dataLen; i++)
{
imageData.data[i] = byteArray[i];
}
ctx.putImageData(imageData, 0, 0);
// create a new element and add it to div
var image = document.createElement('img');
image.width = imageWidth;
image.height = imageHeight;
image.src = canvas.toDataURL();
var div = document.getElementById('img');
div.appendChild(image);