經過WebSocket連接,網頁和服務端能夠實現異步雙向通信。這裏介紹如何從服務端獲取一張圖片,而後傳輸到網頁中顯示出來。html
參考原文:html5
下載SuperWebSocketweb
下載Dynamic .NET TWAINcanvas
閱讀 Program.cs和Test.htmc#
建立一個WinForms工程,導入須要的reference。
websocket
添加namespace:
session
using Dynamsoft.DotNet.TWAIN; using SuperSocket.SocketBase; using SuperWebSocket;
創建Server:
app
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格式:
socket
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端使用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);