开发者

How to save the image to the database after streaming it from an IP camera?

开发者 https://www.devze.com 2023-02-20 10:52 出处:网络
I have a code to stream a snapshot from an IP camera and save it on harddisk. Then I have another code to read it and store it in ms-sql database.

I have a code to stream a snapshot from an IP camera and save it on harddisk. Then I have another code to read it and store it in ms-sql database. I know that it will be more faster if I just stream the image and save it in the database without saving it on the harddisk and read it again. But I don't know how to merge this.

Code to get the image

        string sourceURL = "http://" + ip + "/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);
        bmp.Save(ImagePath);

Then to insert the image to the database:

byte[] imageData = ReadFile(ImageName);
using (SqlConnection cn = new SqlConnection(constr))
  {
  string qry = "update vaiolations set val_image=@ImageData ,valid=1 where id=@OriginalPath ";
  SqlCommand SqlCom = new SqlCommand(qry, cn);
  SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", (object)id));
  SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));
  cn.Open();
  SqlCom.ExecuteNonQuery();
  cn.Close();
  cn.Dispose();
  }
  byte[] ReadFile(string sPath)
   {
     using (FileStream fStream = new FileStream(sPath, FileMode.Open,      FileAccess.Read))
     {
      byte[] data = null;
      FileInfo fInfo = new FileInfo(sPath);
      long numBytes = fInfo.Length;
      BinaryReader br = new BinaryReader(fStream);
      data = br.ReadBytes((int)numBytes);
      return data;
     }
   }

How can I combine these two code snippets to stream the image and 开发者_C百科then immediately insert it into the database?


Why are you converting the incoming bytes to a Bitmap?

You could probably just read the stream to a memory stream, and pass it on to the database:

Stream stream = resp.GetResponseStream();
byte[] data;
using (MemoryStream ms = new MemoryStream())
{
  int num_bytes = 0;
  byte[] temp = new byte[4096];
  while ((num_bytes = stream.Read(temp, 0, temp.Length)) > 0)
    ms.Write(temp, 0, bytes);
  data = ms.ToArray();
}

Then pass data to your database.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号