如何读取从服务器流式传输的jpeg图像

时间:2012-10-19 07:47:05

标签: c# winforms image jpeg tcpclient

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

我在这里以及其他类似问题的网站上阅读了很多帖子,但没有一个能够为我的问题提供解决方案。

我有以下代码,旨在从服务器检索图像并使用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) 。

如果有人能指出我做错了什么或错过了什么,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

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