Stream from C # IP Camera
I have the following code that doesn't work. My link camUrl
works if I load into Firefox and streams from my camera, but nothing appears in my image window at runtime. Any ideas why?
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;
}
}
+3
source to share
2 answers
It looks like your loop for reading from the response stream is wrong. You only get one stream from the response and there will be multiple images on it.
You probably can't stream the responses to Image.FromStream directly - the images are probably encoded in a multipart answer that separates images from text separators. You can read more about the multipart response format in 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;
}
}
}
}
+6
source to share