2012-12-04 56 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); 
}