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

Dani AI

Generated

Most likely cause: GDI+ is refusing to build a Bitmap because the bytes fed into the stream are not a single, valid image. Common reasons in this scenario are: the camera URL returns HTML (error or login page) instead of JPEG/PNG, the endpoint is an MJPEG multipart stream (boundary-delimited frames) rather than a one-shot snapshot, the bytes were truncated while reading, or the Bitmap’s pixel format is incompatible with Emgu’s constructor. ’s idea of creating a Bitmap from the response stream and ’s suggestion to wrap that Bitmap in an Emgu Image are correct in principle, but both require a complete, standalone image in the stream.

Quick checklist to diagnose the problem

  • Confirm the HTTP response StatusCode is 200 and Content-Type is image/jpeg or image/png. If Content-Type is multipart/x-mixed-replace, the response must be parsed per-boundary to extract each JPEG frame rather than read to EOF.

  • Persist the received bytes to disk and open with an external image viewer to see whether the payload is a valid image or HTML/error text. Example debug write:

    File.WriteAllBytes("debug.jpg", buffer.Take(total).ToArray());
  • If the saved file opens as HTML or shows an error page, check camera URL, credentials, and whether a snapshot (single-frame) URL exists. IP cameras often expose both a continuous MJPEG stream and a separate snapshot endpoint.

Emgu-specific notes

  • Emgu accepts a System.Drawing.Bitmap, but the Bitmap should be in a compatible pixel format (24bpp BGR). If the incoming Bitmap has a different PixelFormat, convert it first, for example:

    var compatible = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format24bppRgb);
    using (var g = Graphics.FromImage(compatible)) g.DrawImage(bmp, 0, 0);
    var img = new Image<Bgr, byte>(compatible);

Other cautions

  • Use using blocks to dispose responses/streams, avoid reading an infinite MJPEG stream into a fixed buffer, and prefer a camera snapshot URL when available. ’s reminder that Bitmap derives from System.Drawing.Image is correct, but Emgu.Image<TColor,TDepth> still requires a proper Bitmap conversion before use.

Recommended Answers

All 7 Replies

Try this:

public static Bitmap BitmapFromWeb(string URL)
{
	try {
		// create a web request to the url of the image
		HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
		// set the method to GET to get the image
		myRequest.Method = "GET";
		// get the response from the webpage
		HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
		// create a bitmap from the stream of the response
		Bitmap bmp = new Bitmap(myResponse.GetResponseStream());
		// close off the stream and the response
		myResponse.Close();
		// return the Bitmap of the image
		return bmp;
	} catch (Exception ex) {
		return null; // if for some reason we couldn't get to image, we return null
	}
}

I will try it and let you know if it works. Thanks

I will try it and let you know if it works. Thanks

I had trouble using your code because it returned a bitmap instead of an image. If I used it then I would have to change the Camera class which was also coded to receive image files. I will still try it all the same. Thanks.

??? A bitmap is an image, it's derived from the Image class. Anywhere you use an Image, you can use a Bitmap.

??? A bitmap is an image, it's derived from the Image class. Anywhere you use an Image, you can use a Bitmap.

This is the camera class together with your code. I've indicated where I get the error.

public class Camera
        {
            private string sourceURL;
            private Image<Bgr, Byte> image;

            //Constructor
            public Camera(string cameraURL)
            {
                sourceURL = cameraURL;

            }

            public Image<Bgr, Byte> GetNewImage()
            {
                image = BitmapFromWeb(sourceURL); //error: Cannot implicitly convert 
                return image;                     //type 'System.Drawing.Bitmap' to 
            }                                     //'Emgu.CV.Image<Emgu.CV.Structure.
                                                  //Bgr,byte>'

            public Image<Bgr, Byte> GetOldImage()
            {
                return image;
            }
            public Image<Bgr, Byte> GetImage()
            {
                return image;
            }
            public Image<Bgr, Byte> GetThresholdImage(int threshold)
            {
                image = BitmapFromWeb(sourceURL); //error: Cannot implicitly convert
                                                  //type 'System.Drawing.Bitmap' to 
                                                  //'Emgu.CV.Image<Emgu.CV.Structure.
                                                  //Bgr,byte>'

                return image.ThresholdBinary(new Bgr(threshold, threshold,          
                threshold), new Bgr(255, 255, 255));
            }


                public static Bitmap BitmapFromWeb(string URL)
    {
    try {
    // create a web request to the url of the image
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);

    // set the method to GET to get the image
    myRequest.Method = "GET";

    // get the response from the webpage
    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

    // create a bitmap from the stream of the response
    Bitmap bmp = new Bitmap(myResponse.GetResponseStream());

    // close off the stream and the response
    myResponse.Close();

    // return the Bitmap of the image
    return bmp;

    } catch (Exception ex) {
    return null; // if for some reason we couldn't get to image, we return null
    }
    }

You get that error because your image variable is not a standard .Net Image class.
Does the Emgu.CV namespace have any conversion tools to convert from System.Drawing.Image or System.Drawing.Bitmap to Emgu.CV.Image?
[Edit]
Try this: image = new Image<Bgr, byte>(BitmapFromWeb(sourceURL));

You get that error because your image variable is not a standard .Net Image class.
Does the Emgu.CV namespace have any conversion tools to convert from System.Drawing.Image or System.Drawing.Bitmap to Emgu.CV.Image?
[Edit]
Try this: image = new Image<Bgr, byte>(BitmapFromWeb(sourceURL));

Now, it says "Parameter is not valid" for this code:

Bitmap bmp = new Bitmap(myResponse.GetResponseStream());

I think it has something to do with Bitmap class. When I revised this section of my code, I got the same error at the line I have indicated.

// get bitmap
                    MemoryStream ms = new MemoryStream(buffer, 0, total);
                    Bitmap bmp = (Bitmap)Bitmap.FromStream(ms); //Parameter is not 
                                                                //valid

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

I'm also beginning to think it might have something to do with the .NET framework that I'm using. I'm currently suing .NET 3.5

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.