public async Task <ActionResult> AnalyzeHome(string faceUrl = "", string photoName = "")
        {
            string       requestId     = Guid.NewGuid().ToString();
            int?         contentLength = null;
            VisionHelper vision        = new VisionHelper(GetVisionAPIkey(), fontPath, DateTime.Now, fontPath);
            RichResult   res           = null;

            try
            {
                string postString = string.Empty;

                //using (Stream stream = Request.InputStream)
                //{
                //    byte[] postBytes = new byte[stream.Length];
                //    stream.Read(postBytes, 0, (int)stream.Length);
                //    postString = Encoding.Unicode.GetString(postBytes);
                //    return Json(JsonConvert.SerializeObject(postString), "application/json");
                //}

                Stopwatch stopwatch = Stopwatch.StartNew();
                //Trace.WriteLine(string.Format("Start Analyze Request: RequestId: {0};", requestId));
                if (Request.ContentType == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "BadRequest"));
                }
                if (string.Equals(Request.ContentType, "application/octet-stream"))
                {
                    contentLength = Request.ContentLength;
                    Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                    //var img = System.Drawing.Image.FromStream(Request.InputStream);

                    //return Json(JsonConvert.SerializeObject(img.Width), "application/json");
                    res = await vision.AnalyzeImage(Request.InputStream);
                }
                else if (!string.IsNullOrEmpty(faceUrl) && faceUrl != "undefined")
                {
                    res = await vision.AnalyzeImage(faceUrl);
                }


                //Trace.WriteLine(string.Format("Completed Analyze Request: RequestId: {0};", requestId));
                return(Json(JsonConvert.SerializeObject(res), "application/json"));
            }
            catch (Exception e)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, e.Message));
            }
        }
        public string GetImageUrlByAge(int age, Face face)
        {
            //get images with the given age
            try
            {
                string       requestId  = Guid.NewGuid().ToString();
                VisionHelper vision     = new VisionHelper(GetVisionAPIkey(), fontPath, DateTime.Now, fontPath);
                RichResult   res        = null;
                string       postString = string.Empty;

                var list    = MvcApplication.Age2FaceListMap[age];
                var url     = "";
                var urlList = new List <string>();
                var random  = new Random();
                int idx     = 0;
                foreach (var line in list)
                {
                    var gender     = line.Item1;
                    int faceGender = 1; //male
                    if (!face.Attributes.Gender.Equals("male"))
                    {
                        faceGender = 2;
                    }
                    if (gender != faceGender)
                    {
                        continue;
                    }
                    urlList.Add(line.Item5);
                    idx = random.Next(0, urlList.Count);
                    if (idx > 10 - urlList.Count)
                    {
                        return(urlList[idx]);
                    }
                }
                var getrandomIdx = random.Next(0, urlList.Count - 1);
                return(urlList[getrandomIdx]);
            }
            catch (Exception e)
            {
                return(null);//new HttpStatusCodeResult(HttpStatusCode.InternalServerError, e.Message);
            }
        }
        public async Task <ActionResult> AnalyzeOneImage(string faceUrl = "", string photoName = "")
        {
            string requestId = Guid.NewGuid().ToString();
            //int? contentLength = null;
            VisionHelper vision = new VisionHelper(GetVisionAPIkey(), fontPath, DateTime.Now, fontPath);
            RichResult   res    = null;

            try
            {
                string postString = string.Empty;

                //using (Stream stream = Request.InputStream)
                //{
                //    byte[] postBytes = new byte[stream.Length];
                //    stream.Read(postBytes, 0, (int)stream.Length);
                //    postString = Encoding.Unicode.GetString(postBytes);
                //    return Json(JsonConvert.SerializeObject(postString), "application/json");
                //}

                Stopwatch stopwatch = Stopwatch.StartNew();
                //Trace.WriteLine(string.Format("Start Analyze Request: RequestId: {0};", requestId));
                //if (Request.Content.GetType() == null)
                //{
                //    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "BadRequest");

                //}

                if (!string.IsNullOrEmpty(faceUrl) && faceUrl != "undefined")
                {
                    res = await vision.AnalyzeImage(faceUrl);
                }
                else
                {
                    //if (string.Equals(Request.Headers.GetType(), "application/octet-stream"))
                    //{
                    // contentLength = Request.Content.;
                    //contentLength = Request.ContentLength;
                    //var stream = new MemoryStream();
                    //await Request.Content.CopyToAsync(stream);
                    //stream.Seek(0, System.IO.SeekOrigin.Begin);
                    res = await vision.AnalyzeImage(Request.InputStream);
                }

                if (res.analysisResult.RichFaces.Length > 0)
                {
                    res.stepSize = 5;
                    res.minAge   = res.stepSize * (int)((int)res.analysisResult.RichFaces[0].Attributes.Age / (float)res.stepSize);
                    res.maxAge   = 90;

                    var urls = new List <string>();
                    for (var age = res.minAge; age <= res.maxAge; age += res.stepSize)
                    {
                        var url = GetImageUrlByAge(age, res.analysisResult.RichFaces[0]);
                        urls.Add(!string.IsNullOrEmpty(url) ? url : "");
                    }
                    res.agingImgUrls = urls.ToArray();
                }
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                return(Json(JsonConvert.SerializeObject(res), "application/json"));
            }
            catch (Exception e)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, e.Message));
            }
        }
        private async Task <bool> ProcessMsg(string xml, bool returnImage)
        {
            MsgObject msg = new MsgObject(xml);

            if (msg.MsgType != "image")
            {
                string resString = "请点+号输入一张人物风景照片试试";
                Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>",
                                             msg.FromUserName, msg.ToUserName, resString));
                Response.End();
                return(false);
            }

            bool isDebug = false;

            if (isDebug)
            {
                string debugString = msg.PicUrl;
                Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>",
                                             msg.FromUserName, msg.ToUserName, msg.PicUrl));
                Response.End();
                return(false);
            }



            //string imagePathorUrl = msg.PicUrl;
            //string imagePathorUrl = msg.PicUrl.Replace("https://", "").Replace("http://", "");
            //var ret = vision.AnalyzeImage(msg.PicUrl);
            RichResult ret = null;
            //ret = vision.AnalyzeImage(msg.PicUrl);

            VisionHelper vision = new VisionHelper(GetVisionAPIkey(), fontPath, DateTime.Now, fontPath);


            var task = QuickReturn(vision, msg);

            //md5 = GetMd5(msg.PicUrl);
            md5 = GetMd5(msg.PicUrl + msg.CreateTime.ToString());
            //check data from db
            using (var dbContext = new WeixinDBContext())
            {
                //ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.OpenId == msg.FromUserName && p.PicUrl == msg.PicUrl && p.CreateTime == msg.CreateTime);
                //ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.PicUrl == msg.PicUrl);
                //ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.PicUrl == msg.PicUrl && p.CreateTime == msg.CreateTime);

                //ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.Md5 == md5 && p.CreateTime == msg.CreateTime);
                ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.Md5 == md5);
                if (image != null)
                {
                    Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content><DebugInfo><![CDATA[{3}]]></DebugInfo><ErrorInfo><![CDATA[{4}]]></ErrorInfo></xml>",
                                                 msg.FromUserName, msg.ToUserName, image.ParsedDescription, image.TimeLog, md5));
                    Response.End();
                    return(true);
                }
                dbContext.Dispose();
            }



            ret = await task;

            //when not results in DB and got error
            if (!ret.errorLogs.Equals(""))
            {
                //Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>",
                //        msg.FromUserName, msg.ToUserName, "机器人很忙,请稍后再试"));
                Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content><DebugInfo><![CDATA[{3}]]></DebugInfo><ErrorInfo><![CDATA[{4}]]></ErrorInfo></xml>",
                                             msg.FromUserName, msg.ToUserName, ret.analyzeImageResult, ret.timeLogs, ret.errorLogs));
                Response.End();
            }
            //// Debug mode
            //Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content><DebugInfo><![CDATA[{3}]]></DebugInfo><ErrorInfo><![CDATA[{4}]]></ErrorInfo></xml>",
            //    msg.FromUserName, msg.ToUserName, ret.analyzeImageResult, ret.timeLogs, ret.errorLogs));

            // Production mode
            //Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>", msg.FromUserName, msg.ToUserName, ret.analyzeImageResult));

            //Response.End();


            //save db first without parsedContent
            int id = -1;

            using (var dbContext = new WeixinDBContext())
            {
                ImageStorage image = new ImageStorage();
                image.OpenId     = msg.FromUserName;
                image.CreateTime = msg.CreateTime;
                image.PicUrl     = msg.PicUrl;
                image.Md5        = GetMd5(msg.PicUrl + msg.CreateTime.ToString() + ret.errorLogs);
                //image.PicContent = ret.rawImage;
                image.ParsedUrl         = ret.uploadedUrl;
                image.ParsedDescription = ret.analyzeImageResult + ret.errorLogs;
                image.TimeLog           = ret.timeLogs;
                dbContext.ImageStorages.Add(image);
                dbContext.SaveChanges();
                id = image.Id;
                dbContext.Dispose();
            }

            //write to DB
            //var webClient = new WebClient();
            //var processedImageBytes = webClient.DownloadData(ret.uploadedUrl);

            //using (var dbContext = new WeixinDBContext())
            //{
            //    ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.Id == id);
            //    if (image != null)
            //    {
            //        image.ParsedContent = processedImageBytes;
            //        dbContext.SaveChanges();
            //    }
            //}

            return(true);
        }
        public async Task <HttpResponseMessage> Analyze(string faceUrl = "", string photoName = "")
        {
            string requestId = Guid.NewGuid().ToString();
            //int? contentLength = null;
            VisionHelper vision = new VisionHelper(GetVisionAPIkey(), fontPath, DateTime.Now, fontPath);
            RichResult   res    = null;

            try
            {
                string postString = string.Empty;

                //using (Stream stream = Request.InputStream)
                //{
                //    byte[] postBytes = new byte[stream.Length];
                //    stream.Read(postBytes, 0, (int)stream.Length);
                //    postString = Encoding.Unicode.GetString(postBytes);
                //    return Json(JsonConvert.SerializeObject(postString), "application/json");
                //}

                Stopwatch stopwatch = Stopwatch.StartNew();
                //Trace.WriteLine(string.Format("Start Analyze Request: RequestId: {0};", requestId));
                //if (Request.Content.GetType() == null)
                //{
                //    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "BadRequest");

                //}

                if (!string.IsNullOrEmpty(faceUrl) && faceUrl != "undefined")
                {
                    res = await vision.AnalyzeImage(faceUrl);
                }
                else
                {
                    //if (string.Equals(Request.Headers.GetType(), "application/octet-stream"))
                    //{
                    // contentLength = Request.Content.;
                    //contentLength = Request.ContentLength;
                    var stream = new MemoryStream();
                    await Request.Content.CopyToAsync(stream);

                    stream.Seek(0, System.IO.SeekOrigin.Begin);
                    //var img = System.Drawing.Image.FromStream(Request.InputStream);
                    //return Json(JsonConvert.SerializeObject(img.Width), "application/json");
                    res = await vision.AnalyzeImage(stream);
                }



                //Trace.WriteLine(string.Format("Completed Analyze Request: RequestId: {0};", requestId));
                //return Json(JsonConvert.SerializeObject(res),(Newtonsoft.Json.JsonSerializerSettings) "application/json", System.Text.Encoding.UTF8);


                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                //return Json(JsonConvert.SerializeObject(Json(JsonConvert.SerializeObject(res)).Content));
                result.Content = new StringContent(JsonConvert.SerializeObject(Json(JsonConvert.SerializeObject(res)).Content));//new StringContent(JsonConvert.SerializeObject(res));
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return(result);

                //Error	20	Argument 2: cannot convert from 'string' to 'Newtonsoft.Json.JsonSerializerSettings'
            }
            catch (Exception e)
            {
                return(null);//new HttpStatusCodeResult(HttpStatusCode.InternalServerError, e.Message);
            }
        }