【问题标题】:How to read a jpeg image streamed from a server如何读取从服务器流式传输的 jpeg 图像
【发布时间】:2012-10-19 20:03:32
【问题描述】:

我有一个不断传输 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) .

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

【问题讨论】:

  • 服务器是否使用单个tcp连接传输多个图像?
  • 我无权访问源,但据我所知,它通过单个连接连续循环发送多个图像。
  • 我有这个信息:视频协议示例 [VIDEO-FAULT\|2204771255],视频帧数据包示例 [JPEG-VIDEO\|C2013\|FrameWidth\|FrameHeight\|DateTime\|ImageDataSize]… ImageDataSize 二进制字节形成图像
  • 注意,虽然它说的是视频,但它只是通过 jpeg 发送的
  • “它给出的参数是无效的错误” - 请您显示您遇到的 what 错误,以及使用什么数据?您必须查找正在使用的格式。它是有效的 JPEG 数据吗?您可以测试一下,将字节保存到文件中并使用图像查看器打开它吗?您确定您在假设为 JPEG 的数据中捕获了正确的数据,没有空格或剩余的协议数据(如括号)?

标签: c# winforms image jpeg tcpclient


【解决方案1】:

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

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

【讨论】:

  • 我设法从图像数据包中挑选出标头信息,然后将其余部分(应该是图像数据)作为单独的字符串。不过,这一切看起来都像是 VS2010 调试器中的行话,而且无论我在内存流中放入什么,它总是给出无效的参数。我不知道我应该做什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多