【C#】 MVC4 开发小程序-实现人脸识别-本地和手机预览使用IP测试

333 阅读1分钟

我正在参加「掘金·启航计划」

小程序Camera组件拍照上传图片到指定的服务器(本地或者外网的IP服务器),然后C# MVC后台调用百度人脸识别接口,实现人脸识别功能呢

1、下载微信开发者工具

2、下载微信小程序媒体组件

源码-camera组件-1526881707172

3、在默认组件的拍照按钮的单击事件上添加如下代码

wx.uploadFile({
    url: 'http://166.61.66.66/Home/Upload',
    filePath: res.tempImagePath,
    name: 'file',
    header: { 'content-type': 'multipart/form-data' },
    method: 'POST',
    formData: {'user': 'test'},
    success: function (res) {
        var data = res.data;
        console.log(data);
        var _json = JSON.parse(JSON.parse(data));

        tishi(1,_json);
    },
    fail: function (res) {
        tishi(3,res);
    }
})

function tishi(_t,_v){
    if (_t == 1 && _v.result!=null){
        wx.showModal({
            title: '提示',
            content: '你的颜值分:' + parseInt(_v.result.face_list[0].beauty),
            success: function (res) {
            }
        })
    }
    else{
        wx.showModal({
            title: '提示',
            content: 'type:' + _t + "=" + (_v.errMsg == undefined ? _v.error_msg : _v.errMsg),
            success: function (res) {
            }
        })
    }
}

4、下载百度人脸识别

1)人脸识别技术文档

ai.baidu.com/docs#/Face-… cloud.baidu.com/doc/FACE/Fa…

2)百度云 - 接口需要进入这里创建

console.bce.baidu.com

5、C# MVC 调用人脸识别源码(api调用暂时未实现)

#region 接收Base64编码格式的图片
[HttpPost]
public JsonResult Upload()
{
    string _fileAllPath = "";
    HttpPostedFileBase flogo = Request.Files["file"];
    if (flogo.ContentLength != 0) {
        string name = flogo.FileName; //获取后缀名
        string namejpg = Path.GetExtension(name).ToLower();
        string path = Server.MapPath("../upload/"); //获取上传的路径
        string gid = System.Guid.NewGuid().ToString(); //生成一个新的文件名
        string newname = gid + namejpg; //上传
        _fileAllPath = path + newname;
        flogo.SaveAs(_fileAllPath);
    }
    
    JObject _result= DetectDemo(_fileAllPath); //人脸识别验证
    return Json(_result.ToString());
}

#endregion

public JObject DetectDemo(string _imgpath)
{
    // 设置APPID/AK/SK
    //var APP_ID = "11116994";
    var API_KEY = "百度云申请得到的KEY";
    var SECRET_KEY = "百度云申请得到的KEY";
    var client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);

    client.Timeout = 60000; // 修改超时时间

    var image = _imgpath;
    image = ImgToBase64String(_imgpath);

    var imageType = "URL"; //需要公网可访问的图片

    imageType = "BASE64";

    // 调用人脸检测,可能会抛出网络等异常,请使用try/catch捕获
    var result = client.Detect(image, imageType);
    Console.WriteLine(result);
    // 如果有可选参数 {"face_field", "age","beauty","expression","face_type","glasses","gender"},
    var options = new Dictionary < string, object>{
    {"face_field", "beauty" },
    { "max_face_num", 2 },
    { "face_type", "LIVE" },
    };

    // 带参数调用人脸检测
    result = client.Detect(image, imageType, options);
    return result;
}

 

//imgage图片转base64字符
protected string ImgToBase64String(string Imagefilename)
{
    try {
        Bitmap bmp = new Bitmap(Imagefilename);
        MemoryStream ms = new MemoryStream();
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] arr = new byte[ms.Length];
        ms.Position = 0;
        ms.Read(arr, 0, (int)ms.Length);
        ms.Close();
        return Convert.ToBase64String(arr);
    }
    catch (Exception ex) {
        return null;
    }
}

6、小程序本地开发调试和手机预览,建议进行如下操作

1)微信开发者工具-点击详情-在项目设置:勾选上-不校验安全域名

2)手机预览,需要打开调试模式才能请求到IP地址

3)如果以上两者都无法访问,需要检查ip设置是否正确,以及IP服务器是否被防火墙屏蔽了