调用System.Drawing.Image.FromStream()时出现ArgumentException

时间:2011-03-04 00:33:49

标签: c#

我是一名C#初学者,面临有关将图像从客户端发送到服务器的问题。我使用以下代码:

客户:

try
{
    Bitmap desktopBMP = CaptureScreen.CaptureDesktop();
    Image image = (Image)desktopBMP;
    MemoryStream ms = new MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

    if (m_clientSocket != null)
    {
       byte[] data = ms.ToArray();
        m_clientSocket.Send(data);
    }
}
catch (Exception e)
 {
       sending = false;
        MessageBox.Show(e.Message);
 } 

服务器:

 // This the call back function which will be invoked when the socket
 // detects any client writing of data on the stream

 static int i = 0;
 public void OnDataReceived(IAsyncResult asyn)
 {  
     SocketPacket socketData = (SocketPacket)asyn.AsyncState;
     try
     {
          // Complete the BeginReceive() asynchronous call by EndReceive() method
          // which will return the number of characters written to the stream 
          // by the client
          int iRx = socketData.m_currentSocket.EndReceive(asyn);
          byte[] data = new byte[iRx];
          data = socketData.dataBuffer;
          MemoryStream ms = new MemoryStream(data);
          Image image = Image.FromStream(ms);
          image.Save(i + socketData.m_clientNumber+".jpg");
          i++;

      // Continue the waiting for data on the Socket
         WaitForData(socketData);

     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
     } 


// Start waiting for data from the client
   public void WaitForData(SocketPacket socketPacket)
   {
       try
       {
         if (pfnWorkerCallBack == null)
         {
             // Specify the call back function which is to be 
             // invoked when there is any write activity by the 
             // connected client
             pfnWorkerCallBack = new AsyncCallback(OnDataReceived);  
         }

         socketPacket.m_currentSocket.BeginReceive(socketPacket.dataBuffer, 
                                                   0,
                                                   socketPacket.dataBuffer.Length,
                                                   SocketFlags.None,
                                                   pfnWorkerCallBack,
                                                   socketPacket
                                                  );
       }
       catch (Exception e)
       {
           MessageBox.Show(e.Message);
       }
    }

客户端每隔100毫秒发送一次图像,这种情况很有效,但有时服务器中调用的“System.Drawing.Image.FromStream()”函数会引发“ArgumentException”。

我在这里做错了什么?我该如何纠正呢?

由于

1 个答案:

答案 0 :(得分:1)

查看MSDN page for Image.FromStream,它指出该参数为null或在抛出该异常时包含无效图像。您是否还可以将图像数据的哈希值发送到服务器,然后可以使用它来验证您的图像数据在传输过程中是否已损坏?如果它已损坏,服务器可以通知客户端它应该重新发送图像。我怀疑你运行的数据太多了,你偶然会收到一些损坏的数据。

还要添加一个临时检查,以确保在调试此问题时,socketData.dataBuffer未以某种方式设置为null。