2012-10-19 59 views
0

我有一台服务器不断地传输jpeg图像,如时间推移视频源。我需要在C#WinForm TCP客户端中显示这些图像,并且遇到流式处理问题。如何读取从服务器流式传输的jpeg图像

我在这里和其他网站上阅读了大量的帖子,但其中没有一个能够提供解决方案来解决我的问题。

我有下面的代码,其目的是从该服务器检索该图像并使用PictureBox控件显示它:(存在图像流中的头信息)

while (true) 
{ 
    NetworkStream stream = m_client.GetStream(); //Get the data stream from the server 

    //Load Image 
    while (stream.DataAvailable) 
    { 
     byte[] buffer = new byte[m_client.ReceiveBufferSize]; 
     stream.Read(buffer, 0, buffer.Length); 
     string tempString = System.Text.Encoding.ASCII.GetString(buffer); 
     //split header info and data into separate strings 
     string[] splitString = tempString.Split(new string[] { "]" }, 2, StringSplitOptions.None); 
     splitString[0] = splitString[0].Replace(@"\", ""); 
     //split header info into separate strings for use later 
     string[] imageInfo = splitString[0].Split('|'); 

     int size = Convert.ToInt32(tempString.Length); 
     //int offset = splitString[0].Length; 
     buffer = new byte[size]; 
     stream.Read(buffer, 0, buffer.Length); 

     //Convert Image Data To Image 
     MemoryStream imageStream = new MemoryStream(buffer, 0, buffer.Length); 
     imageStream.Position = 0; 
     Bitmap img = new Bitmap(imageStream); 

     //set the image display box properties 
     VideoBox.Width = img.Width; 
     VideoBox.Height = img.Height; 
     VideoBox.Image = img; //Show the image in the picturebox 
    } 
    stream.Flush(); 
} 

目前这个代码运行,只要到Bitmap img = new Bitmap(imageStream);它给出的参数是无效的错误。

这是我第一次做这个,所以在接下来的尝试中有点失落,我花了最后一天尝试不同的解决方案,但这个似乎是迄今为止最好的(我认为:s )。

我将不胜感激,如果任何人都可以指出我做错了或失踪。

+0

服务器是否使用单个TCP连接传输多个图像? – empi

+0

我无法访问源代码,但据我所知,它通过单个连接以连续的周期发送多个图像。 – enigma20

+0

我有这样的信息:视频协议示例\ [VIDEO-FAULT \ | 2204771255 \],视频帧数据包示例\ [JPEG-VIDEO \ | C2013 \ | FrameWidth \ | FrameHeight \ | DateTime \ | ImageDataSize \] ... ImageDataSize binary bytes形成图像 – enigma20

回答

0

首先,您必须能够从流中选择单个图像。您可以检查服务器是否使用某种传输帧,或者您必须检查图像头以确定哪部分流代表单个图像。只有当你选择了表示单个图像的数据时,才能将它传递给位图构造函数。

当使用TCP连接时,你必须明确地引入一些帧格式。否则,您将无法确定您的内容开始和结束的位置。

+0

我设法从图像数据包中挑选标题信息,然后将其余部分(应该是图像数据)作为单独的字符串。不过,在VS2010调试器中,这一切看起来都像行话一样,无论我放在内存流中,它总是给参数无效。我不知道我应该怎么做 – enigma20

相关问题