ck22
ck22

Reputation: 61

ArgumentException Occurred: Parameter is not valid

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.

Upvotes: 2

Views: 2403

Answers (3)

SteveCav
SteveCav

Reputation: 6729

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/

Upvotes: 0

Andrei
Andrei

Reputation: 56716

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.

Upvotes: 2

confucius
confucius

Reputation: 13327

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

Upvotes: 0

Related Questions