【问题标题】:Slow performance in reading from stream .NET从流 .NET 中读取性能缓慢
【发布时间】:2011-03-20 17:24:34
【问题描述】:

我有一个监控系统,我想在警报触发时保存来自摄像头的快照。 我已经尝试了很多方法来做到这一点……一切都很好,从相机流式传输快照,然后将其保存为 jpg 在电脑中……。图片(jpg格式,1280*1024,140KB)..没关系 但我的问题在于应用程序性能...... 该应用程序需要大约 20 ~ 30 秒来读取蒸汽,这是不可接受的,因为该方法将每 2 秒调用一次。我需要知道该代码有什么问题以及如何才能更快地获得它。 ? 提前谢谢了 代码:

string sourceURL = "http://192.168.0.211/cgi-bin/cmd/encoder?SNAPSHOT";
byte[] buffer = new byte[200000];
int read, total = 0;
WebRequest req = (WebRequest)WebRequest.Create(sourceURL);
req.Credentials = new NetworkCredential("admin", "123456");
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
while ((read = stream.Read(buffer, total, 1000)) != 0)
  {
      total += read;
  }
Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0,total));
string path = JPGName.Text+".jpg";
bmp.Save(path);

【问题讨论】:

    标签: c# image stream


    【解决方案1】:

    我无法尝试 WebResponse 流的网络行为,但您处理了两次流(一次在循环中,一次在内存流中)。

    我不认为这是整个问题,但我会尝试一下:

         string sourceURL = "http://192.168.0.211/cgi-bin/cmd/encoder?SNAPSHOT";
         WebRequest req = (WebRequest)WebRequest.Create(sourceURL);
         req.Credentials = new NetworkCredential("admin", "123456");
         WebResponse resp = req.GetResponse();
         Stream stream = resp.GetResponseStream();
         Bitmap bmp = (Bitmap)Bitmap.FromStream(stream);
         string path = JPGName.Text + ".jpg";
         bmp.Save(path);
    

    【讨论】:

      【解决方案2】:

      我非常怀疑这段代码是否是问题的原因,至少对于第一个方法调用(但请阅读下文)。

      从技术上讲,您可以在不先保存到内存缓冲区的情况下生成位图,或者如果您也不需要显示图像,则可以保存原始数据而无需构建位图,但这无济于事在多秒改进性能方面。您是否检查过使用浏览器、wget、curl 或任何工具从该 URL 下载图像需要多长时间,因为我怀疑编码源出了问题。

      你应该做的是清理你的资源;正确关闭流。如果您定期调用此方法,这可能会导致问题,因为 .NET 只会在任何时候打开几个到同一主机的连接。

      // Make sure the stream gets closed once we're done with it
      using (Stream stream = resp.GetResponseStream())
      {
          // A larger buffer size would be benefitial, but it's not going
          // to make a significant difference.
          while ((read = stream.Read(buffer, total, 1000)) != 0)
          {
              total += read;
          }
      }
      

      【讨论】:

        【解决方案3】:

        尝试读取更大的数据片段,每次超过 1000 字节。例如,我认为没有问题

        read = stream.Read(buffer, 0, buffer.Length);
        

        【讨论】:

        • 除了这可能读取比数据写入流更快,这会导致数据丢失。但无论如何,主要的想法是一次读取更大的字节块。
        【解决方案4】:

        试试这个下载文件。

        using(WebClient webClient = new WebClient())
        {
            webClient.DownloadFile("http://192.168.0.211/cgi-bin/cmd/encoder?SNAPSHOT", "c:\\Temp\myPic.jpg");
        }
        

        您可以使用 DateTime 在镜头上添加独特的印记。

        【讨论】:

          猜你喜欢
          • 2015-11-09
          • 2015-01-17
          • 1970-01-01
          • 2020-12-19
          • 2014-11-08
          • 1970-01-01
          • 2020-09-18
          • 1970-01-01
          • 2018-09-20
          相关资源
          最近更新 更多