2012-12-04 57 views
0

我試圖從客戶端到服務器流對面的攝像頭,但我很難從字節數組轉換回服務器上的位圖。位圖轉換

下面的代碼:

public void handlerThread() 
{ 
    Socket handlerSocket = (Socket)alSockets[alSockets.Count-1]; 
    NetworkStream networkStream = new 
    NetworkStream(handlerSocket); 
    int thisRead=0; 
    int blockSize=1024; 
    Byte[] dataByte = new Byte[blockSize]; 
    lock(this) 
    { 
     // Only one process can access 
     // the same file at any given time 
     while(true) 
     { 
      thisRead=networkStream.Read(dataByte,0,blockSize); 

      pictureBox1.Image = byteArrayToImage(dataByte); 
      if (thisRead==0) break; 
     } 
     fileStream.Close(); 
    } 
    lbConnections.Items.Add("File Written"); 
    handlerSocket = null; 
} 

public Image byteArrayToImage(byte[] byteArrayIn) 
{ 
    MemoryStream ms = new MemoryStream(byteArrayIn); //here is my error 
    Image returnImage = Image.FromStream(ms); 
    return returnImage; 
} 

在上面標明我得到「參數無效」試圖回圖像和崩潰時轉換點。任何關於我在做什麼的錯誤?

+0

似乎我的問題是我的緩衝區太小。首先需要做更多的測試。 – windowskm

回答

0

注意此位: Image.Save(..) throws a GDI+ exception because the memory stream is closed

您可以創建一個擴展方法或刪除「本」的傳統方法。這看起來與您的代碼相同,所以我想知道是否有某種類型的編碼或其他問題與創建基礎字節數組有關?

public static Image ToImage(this byte[] bytes) 
{ 
    // You must keep the stream open for the lifetime of the Image. 
    // Image disposal does clean up the stream. 

    var stream = new MemoryStream(bytes); 
    return Image.FromStream(stream); 
}