来自IP cam C#的流

时间:2014-10-23 11:57:55

标签: c# stream ip picturebox

我有以下代码无效。如果我加载到Firefox并从我的摄像头流式传输,我的camUrl链接可以正常工作,但在运行时我的图片框中没有显示任何内容。有什么想法吗?

        public Thread _camThread;
        private string camUrl = "http://my-domain-ip:2080/videostream.cgi?user=admin&pwd=password";
        public HttpWebRequest webReq;
        public WebResponse webRes;
        public Stream sr;

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (_camThread == null) _camThread = new Thread(new ThreadStart(RunCam));
            _camThread.Start();
        }

        private void RunCam()
        {
            try
            {
                webReq = (HttpWebRequest)WebRequest.Create(camUrl);
                webReq.AllowWriteStreamBuffering = true;
                webReq.Timeout = 20000;
                using (webRes = webReq.GetResponse())
                {
                    while ((sr = webRes.GetResponseStream()) != null)
                    {
                        image.Image = Image.FromStream(sr);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (_camThread.IsAlive)
            {
                _camThread.Abort();
                _camThread = null;
            }
        }

2 个答案:

答案 0 :(得分:6)

看起来您从响应流中读取的循环不正确。您只能从响应中获取一个流,并且它上面会有多个图像。

您可能无法直接将响应流传递给Image.FromStream - 图像可能以多部分响应进行编码,该响应将图像与文本分隔符分开。您可以在RFC2046了解有关多部分回复格式的更多信息。

using (webRes = webReq.GetResponse())
{
    using (sr = webRes.GetResponseStream())
    {
        // continuously read images from the response stream until error
        while (true)
        {
            try
            {
                // note: the line below probably won't work, you may need to parse
                // the next image from the multi-part response stream manually
                image.Image = Image.FromStream(sr);


                // if the above doesn't work, then do something like this:
                // var imageBytes = ParseNextImage(sr);
                // var memoryStream = new MemoryStream(imageBytes);
                // image.Image = Image.FromStream(memoryStream);
            }
            catch(Exception e)
            {
                Console.WriteLine("Aborting read from response stream due to error {0}", e);
                break;
            }
        }
    }
}

答案 1 :(得分:1)

camUrl是否会返回图片?

尝试调试sr = webRes.GetResponseStream(),如果它不为空,请尝试image.Invalidate()image.Update()

More information about invalidate, update and refresh