主要方法:
using System.IO; using System.Drawing; using System.Drawing.Imaging;
public ActionResult UploadFaceImg(string faceImg, string xfNo, string Eid) { string dic = System.AppDomain.CurrentDomain.BaseDirectory.ToString(); #region 检测是否有人脸,并获取其坐标 string results = haveFace(faceImg); if (string.IsNullOrEmpty(results)) {
//如果没有人脸则返回 return Content(new ResParameter { code = ResponseCode.success, info = "2", data = null }.ToJson()); }
//定义坐标系 int x = 0; int y = 0; int width = 0; int height = 0; double dx = 0; double dy = 0; double dwidth = 0; double dheight = 0; var re = results.Split(new char[] { ',' }); for (var i = 0; i < re.Length; i++) { dx = double.Parse(re[0]); dy = double.Parse(re[1]); dwidth = double.Parse(re[2]); dheight = double.Parse(re[3]); }
//此处为坐标增减了一定的数据,因为百度拿到人脸坐标就只有脸,连头发都没有,太丑了。 x = (int)dx - 100; y = (int)dy - 100; width = (int)dwidth + 160; height = (int)dheight + 200; #endregion
//根据坐标系裁切人脸
#region 根据坐标剪切出人脸
string fileUrl = "/Resource/FaceImg/";//存储人脸图片的文件夹
string bpmfile =dic+ fileUrl + DateTime.Now.ToString("yyMMddhhmmss") + "-2.png";//裁剪后的照片
ToBitmap(fasebase, bpmfile, x, y, width, height);
#endregion
////如果图片太大,那么需要压缩图片大小
string fImgNew = fileUrl + DateTime.Now.ToString("yyMMddhhmmss") + "-1.jpg";//压缩后的照片名称
string fileNew = dic + fImgNew;
GetPicThumbnail(bpmfile, fileNew, 20);
return Content(new ResParameter { code = ResponseCode.success, info = "1", data = null }.ToJson());
}
#region 百度检测人脸,若有则返回其坐标 public string haveFace(string faceimg) { string results = ""; DateTime dt1 = DateTime.Now; string token = "百度账户token"; string host = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + token; Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host); request.Method = "post"; request.KeepAlive = true; String str = "{\"image\":\"" + faceimg.Replace(" ", "+") + "\",\"image_type\":\"BASE64\",\"face_field\":\"quality,angle,mask\"}"; byte[] buffer = encoding.GetBytes(str); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string result = reader.ReadToEnd(); int facenum = 0; if (result.ToJObject()["error_msg"].ToString() == "SUCCESS") { facenum = result.ToJObject()["result"]["face_num"].ToInt(); } if (facenum > 0) { var j_result = result.ToJObject(); Double x = j_result["result"]["face_list"][0]["location"]["left"].ToDouble(); Double y = j_result["result"]["face_list"][0]["location"]["top"].ToDouble(); Double width = j_result["result"]["face_list"][0]["location"]["width"].ToDouble();//人脸区域宽度 Double height = j_result["result"]["face_list"][0]["location"]["height"].ToDouble();//人脸区域高度 results = x + "," + y + "," + width + "," + height; } return results; } #endregion
#region 截取图片 //转换为位图 public static Bitmap ToBitmap(string base64, string fileUrl,int x,int y,int width,int height) { byte[] imageBytes = Convert.FromBase64String(base64); MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); ms.Write(imageBytes, 0, imageBytes.Length); Image image = Image.FromStream(ms, true); Bitmap bitmapQR = CutImage(image, new Rectangle(x, y, width, height)); //将为图存储到本地 bitmapQR.Save(fileUrl, System.Drawing.Imaging.ImageFormat.Bmp); return bitmapQR; } #endregion
/// <summary> /// 图片压缩 /// </summary> /// <param name="sFile">图片路径</param> /// <param name="outPath">保存路径</param> /// <param name="flag">图片压缩值</param> /// <returns></returns> public static bool GetPicThumbnail(string sFile, string outPath, int flag) { System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat; //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径 } else { iSource.Save(outPath, tFormat); } return true; } catch(Exception ex) { return false; } finally { iSource.Dispose(); iSource.Dispose(); } }