0

我有一台服务器,它不断传输 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)。

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

4

1 回答 1

0

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

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

于 2012-10-19T08:11:48.537 回答