多线程以及抓取图片。

 public partial class CameraFrm : Form
    {
        //private IOrderSyncServices orderBE = AccessOrderSync.GetOrderSyncServices();
        //private string sysCode = "";
        private string url = @"http://supervise.eat.sc/Video/upload";
        public CameraFrm()
        {
            InitializeComponent();
            //SystemInfo si = new SystemInfo();
            //this.sysCode = si.getRNum();
            //DataSet ds = SQLiteHelper.Query("select sub_guid,openid from sc_license where code='" + this.sysCode + "'");
            //string guid = ds.Tables[0].Rows[0]["openid"].ToString();//总店的GUID FA3BF2D8-1FC7-3B6F-90F0-60AA22525305
            //string suid = ds.Tables[0].Rows[0]["sub_guid"].ToString();//分店GUID 19DBBC08-D4C9-CE21-879A-8927F8DC8C99
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = true;
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 摄像头ID
        /// </summary>
        public string cameraid { get; set; }//摄像头ID
        public string ACTIVE { get; set; }//是否启动摄像头start=启动
        public string guid { get; set; }//总店GUID
        public string suid { get; set; }//分店GUID
        private bool falg { get; set; }//是否启动
        private string sPath { get; set; }//摄像头抓取图片存放地址
        private string cameraFile { get; set; }//摄像头地址
        private void CameraFrm_Load(object sender, EventArgs e)
        {
            this.ImageFile();
            this.ResultCameraFile(this.cameraid);
            this.timer1.Enabled = true;
            if (this.ACTIVE == "start")
            {
                this.falg = true;
                this.CreateUpdata();
            }
            else
            {
                this.falg = false;
                Application.ExitThread();
                this.Close();
            }
        }
        private int count = 0;
        private string point = "";
        private string strs = "图片上传中";
        private void timer2_Tick(object sender, EventArgs e)
        {
            this.label1.Text = this.strs + this.point;
            this.point = this.point + ".";
            if (this.count >= 5)
            {
                this.count = 0;
                this.point = ".";
            }
            this.count++;
        }
        public void CreateUpdata()
        {
            try
            {
                Thread mainThread = new Thread(new ThreadStart(CreateThread));
                mainThread.Start();
            }
            catch (Exception ex)
            {
                Application.ExitThread();
                this.Close();
            }
        }
        private void CreateThread()
        {
            try
            {
                while (falg)
                {
                    Thread minorThread = new Thread(new ThreadStart(ImageCameralUpload));
                    minorThread.Start();
                    Thread.Sleep(700);
                }
            }
            catch (Exception ex)
            {
                Application.ExitThread();
                this.Close();
            }
        }
        /// <summary>
        ///向服务器上传摄像头所拍的照片
        /// </summary>
        public void ImageCameralUpload()
        {
            try
            {
                string sign = "";// ResultPostArguments(appid, cameraid, guid, suid);
                string OpathImage = this.GetPicUrl();
                string str = PostData(this.url, sign, this.guid, this.suid, this.cameraid, OpathImage);
                if (str != "")
                {
                    var jObject = JObject.Parse(str);
                    if (jObject["code"].ToString()=="0")
                    {
                       File.Delete(OpathImage);
                    }
                    else
                    {
                        this.falg = false;
                        timer1.Enabled = false;
                        Thread.Sleep(5000);
                        File.Delete(OpathImage);
                        Application.ExitThread();
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Application.ExitThread();
                this.Close();
            }
        }
        //获取签名
        private string ResultPostArguments(string appid, string cameraid, string guid, string suid)
        {
            int count = 0;
            StringBuilder builder = new StringBuilder();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("cameraid", cameraid);
            dic.Add("guid", guid);
            dic.Add("suid", suid);
            //升序排列
            var dicSort = from objDic in dic orderby objDic.Key select objDic;
            foreach (KeyValuePair<string, string> kvp in dicSort)
            {
                count++;
                builder.Append(kvp.Key + "=" + kvp.Value);
                if (count != dic.Count)
                {
                    builder.Append("&");
                }
            }
            string appkey = "f6ac54df8aee6e3c0a4d1ac0b69db6f7";
            string sign = md5(builder.ToString() + appid + appkey).ToLower();
            return sign;
        }
        //MD5加密
        private string md5(String input)
        {
            MD5CryptoServiceProvider Md5 = new MD5CryptoServiceProvider();
            return BitConverter.ToString(Md5.ComputeHash(Encoding.UTF8.GetBytes(input))).Replace("-", "");
        }
        /// <summary>
        /// 向服务器上传图片
        /// </summary>
        /// <param name="url">服务器地址</param>
        /// <param name="sign">签名</param>
        /// <param name="appId">APPID</param>       
        /// <param name="jpegPath">图片地址</param>
        /// <returns></returns>
        public string PostData(string url, string sign, string guid, string suid, string cameraid, string imageFile)
        {
            try
            {
                FileStream file = new FileStream(imageFile, FileMode.Open);
                byte[] bb = new byte[file.Length];
                file.Read(bb, 0, (int)file.Length);
                file.Close();
                
                MultiPartFormData form = new MultiPartFormData();
                form.AddFormField("sign", sign);
                form.AddFormField("guid", guid);
                form.AddFormField("suid", suid);
                form.AddFormField("cameraid", cameraid);
                form.AddStreamFile("img", Path.GetFileName(imageFile), bb);
                form.PrepareFormData();
                form.GetFormData();
                string contentType = "multipart/form-data; boundary=" + form.Boundary;
                HttpUploadHelper help = new HttpUploadHelper();
                HttpItem item = new HttpItem()
                {
                    URL = url,
                    Accept = "text/*",
                    ContentType = contentType,
                    Method = "POST",
                    PostDataType = PostDataType.Byte,
                    Timeout = 1000000,
                    ReadWriteTimeout = 3000000,
                    PostdataByte = form.GetFormData().ToArray(),
                    Encoding = Encoding.UTF8,
                };
                item.Header.Add("Pragma", "no-cache");
                item.Header.Add("DNT", "1");
                HttpResult result = help.GetHtml(item);
                string html = result.Html;
                return html;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// 抓取网络图片保存到本地
        /// </summary>
        /// <returns>本地路径</returns>
        private string GetPicUrl()
        {
            //string sPath = @"Data\Img\";
            //if (!Directory.Exists(sPath))
            //{
            //    Directory.CreateDirectory(sPath);
            //}
            Bitmap img = null;
            HttpWebRequest req;
            HttpWebResponse res = null;
            try
            {
                System.Uri httpUrl = new System.Uri(this.cameraFile);
                req = (HttpWebRequest)(WebRequest.Create(httpUrl));
                req.Timeout = 180000; //设置超时值10秒
                //req.UserAgent = "XXXXX";
                //req.Accept = "XXXXXX";
                req.Method = "GET";
                res = (HttpWebResponse)(req.GetResponse());
                img = new Bitmap(res.GetResponseStream());//获取图片流                
                img.Save(this.sPath + DateTime.Now.ToFileTime().ToString() + ".jpg");//随机名
            }
            catch (Exception ex)
            {
                string aa = ex.Message;
            }
            finally
            {
                res.Close();
            }
            return sPath;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.falg = true;
           // ImageMessage();
            CreateUpdata();
        }
    
        private void ImageFile()
        {
            this.sPath = @"Data\Img\";
            if (!Directory.Exists(this.sPath))
            {
                Directory.CreateDirectory(this.sPath);
            }
        }
        private void ResultCameraFile(string cameraid)
        {
            string sql = "select cameralPictureUrl from camera_manager where Id='" + cameraid + "'AND cameralState='0'";
            this.cameraFile = "http://192.168.0.37:81/snapshot.cgi?user=admin&pwd=";
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

posted on 2015-05-07 16:22  zrSoldier  阅读(269)  评论(0编辑  收藏  举报