来自IP摄像头C#的流

本文关键字:的流 摄像头 IP 来自 | 更新日期: 2023-09-27 18:27:38

我有以下代码不起作用。如果我加载到Firefox并从我的摄像头流式传输,我的camUrl链接就可以工作,但在运行时我的picturebox中什么都不显示。有什么想法吗?

        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;
            }
        }

来自IP摄像头C#的流

从响应流中读取的循环似乎不正确。你只能从一个响应中得到一个流,它上面会有多个图像

您可能无法将响应流直接传递给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;
            }
        }
    }
}

camUrl是否返回图像?

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

有关无效、更新和刷新的更多信息