Slow performance when reading from a .NET stream.

I have a monitoring system, and I want to save a snapshot from the camera when an alarm is triggered. I tried many methods to do this ... and it all works great, stream a snapshot from the camera, and then save it as a jpg in PC. picture (jpg format, 1280 * 1024,140KB) .. Thats fine But my problem is application performance ... The application will need about 20-30 seconds to read a couple, this is not acceptable because this method will be called every two seconds. I need to know what is wrong with this code, and how can I get it much faster than this.? Thanks in advance Code:

string sourceURL = "http://192.168.0.211/cgi-bin/cmd/encoder?SNAPSHOT";
byte[] buffer = new byte[200000];
int read, total = 0;
WebRequest req = (WebRequest)WebRequest.Create(sourceURL);
req.Credentials = new NetworkCredential("admin", "123456");
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
while ((read = stream.Read(buffer, total, 1000)) != 0)
  {
      total += read;
  }
Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0,total));
string path = JPGName.Text+".jpg";
bmp.Save(path);
+3
source share
4 answers

, , ( ).

Bitmap , , , Bitmap, . , , URL- , wget, curl , , - .

-, , ; . , , .NET .

// Make sure the stream gets closed once we're done with it
using (Stream stream = resp.GetResponseStream())
{
    // A larger buffer size would be benefitial, but it not going
    // to make a significant difference.
    while ((read = stream.Read(buffer, total, 1000)) != 0)
    {
        total += read;
    }
}
+3

WebResponse, ( ).

, , :

     string sourceURL = "http://192.168.0.211/cgi-bin/cmd/encoder?SNAPSHOT";
     WebRequest req = (WebRequest)WebRequest.Create(sourceURL);
     req.Credentials = new NetworkCredential("admin", "123456");
     WebResponse resp = req.GetResponse();
     Stream stream = resp.GetResponseStream();
     Bitmap bmp = (Bitmap)Bitmap.FromStream(stream);
     string path = JPGName.Text + ".jpg";
     bmp.Save(path);
+1

Try to read large pieces of data than 1000 bytes at a time. I see no problems, for example,

read = stream.Read(buffer, 0, buffer.Length);
+1
source

Try downloading the file.

using(WebClient webClient = new WebClient())
{
    webClient.DownloadFile("http://192.168.0.211/cgi-bin/cmd/encoder?SNAPSHOT", "c:\\Temp\myPic.jpg");
}

You can use DateTime to set a unique mark on the picture.

0
source

Source: https://habr.com/ru/post/1756413/


All Articles