1

I have this code snippet (see below) that I'm working with. I keep getting the above error. Can anyone tell me what I'm doing wrong and how to solve it? Thanks.

private static Image<Bgr, Byte> GetImageFromIPCam(string sourceURL)
{
    byte[] buffer = new byte[300000];
    int read, total = 0;

    // create HTTP request
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sourceURL);

    // get response
    WebResponse resp = req.GetResponse();

    // get response stream
    Stream stream = resp.GetResponseStream();

    // read data from stream
    while ((read = stream.Read(buffer, total, 1000)) != 0)
    {
        total += read;
    }

    // get bitmap
    Bitmap bmp = (Bitmap)Bitmap.FromStream( //error occurs here
        new MemoryStream(buffer, 0, total)); //error occurs here

    Image<Bgr, Byte> img = new Image<Bgr, byte>(bmp);

    return img;
}

I would like to add that, this program works fine from time to time. Some days it doesn't work at all and I don't understand why. I have a presentation and I cannot afford for the program to fail to run on that day.

Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
ck22
  • 41
  • 8

3 Answers3

2

According to MSDN constructor

public MemoryStream(byte[] buffer, int index, int count)

throws an ArgumentException when the sum of index and count is greater than the length of buffer. Verify that total variable contains correct value that is smaller than buffer.

Andrei
  • 55,890
  • 9
  • 87
  • 108
0

This error is seen a lot with people trying to get the current image of an IP Camera. The reason is that many IP Cameras render their own web pages at the URL and you're treating a web page as an image, which will never work.

Most IP Cameras have a URL that will give the current image, you should be using that instead. If you don't know what it is, here's a starting point:

http://www.bluecherrydvr.com/2012/01/technical-information-list-of-mjpeg-and-rtsp-paths-for-network-cameras/

SteveCav
  • 6,649
  • 1
  • 50
  • 52
0

ArgumentException

The sum of offset in your case "0" and count in your case "total" is larger than the buffer length.

see this

try

byte [] buffer= new byte[total]; 

make this statement after the while loop

confucius
  • 13,127
  • 10
  • 47
  • 66
  • Don't you mean before the while loop? When I put "byte[] buffer = new byte[total];" after the while loop, I get the error message saying "cannot use local variable "buffer" before it is declared, which is accurate. However when I put it before the while loop, I get this message: ArgumentOutOfRange Exception:Specified argument was out of the range of valid values. Parameter name: size for this code line: while ((read = stream.Read(buffer, total, 1000)) != 0) – ck22 Sep 08 '11 at 16:47