yanjinhui
2025-06-12 95ac5296182b763d12125c1d47f53c00632ffc41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using FaceAI;
 
namespace WIDESEAWCS_Common
{
    public class BaiDuFaceHelper
    {
        #region 人脸识别API
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {
            //string url = string.Format("https://aip.baidubce.com/oauth/2.0/token?client_id={0}&client_secret={1}&grant_type={2}", "TqFQHXSNt6Z7cPQ4vDBfBNjq", "0cli6I6s8JFz3qM1Czi5ciRpDqrJuVvm", "client_credentials");
            //string returnStr = BDWebRequest(url, "", "POST");
 
            //NLog.LogManager.GetCurrentClassLogger().Trace("百度人脸识别返回:" + returnStr);
            //BDToken token = JsonConvert.DeserializeObject<BDToken>(returnStr);
            //token.getdate = DateTime.Now.ToString();
 
            //return token.access_token;
 
 
            var str = "24.83aee44079e5a27530bc72d5ec7049a3.2592000.1746152354.282335-118294290";
            return str;
        }
 
        public static string BDWebRequest(string url, string data, string method)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = string.IsNullOrEmpty(method) ? "POST" : method.ToUpper();
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22";
                request.ServicePoint.Expect100Continue = false;
                request.Timeout = 1000 * 60;
                request.ContentType = "application/x-www-form-urlencoded";
                if (!string.IsNullOrEmpty(method) && method.ToUpper() == "POST" && !string.IsNullOrEmpty(data))
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(data);
                    request.ContentLength = byteArray.Length;
                    using (Stream myRequestStream = request.GetRequestStream())
                    {
                        myRequestStream.Write(byteArray, 0, byteArray.Length);
                    }
                }
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
                using (Stream response = myHttpWebResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(response, Encoding.UTF8))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch { return ""; }
        }
 
 
        /// <summary>
        /// 人脸检测与属性分析
        /// </summary>
        /// <returns></returns>
        public static string FaceDetect(string path)
        {
            string token = GetAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + token;
            var imgbase64 = GetFileContentAsBase64(path);
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "POST";
            request.KeepAlive = true;
            String str = "{\"image\":\"" + imgbase64 + "\",\"image_type\":\"BASE64\"}";
            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();
 
            NLog.LogManager.GetCurrentClassLogger().Trace("人脸检测与属性分析:" + result);
            return result;
        }
 
        /// <summary>
        /// 创建用户人脸识别组
        /// </summary>
        /// <returns></returns>
        public static string GroupAdd(string group)
        {
            string token = GetAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/add?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            String str = "{\"group_id\":\"" + group + "\"}";
            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();
            NLog.LogManager.GetCurrentClassLogger().Trace("创建用户组:" + result);
            return result;
        }
 
        /// <summary>
        /// 获取文件base64编码
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>base64编码信息,不带文件头</returns>
        //public static string GetFileContentAsBase64(string path)
        //{
        //    using (FileStream filestream = new FileStream(path, FileMode.Open))
        //    {
        //        byte[] arr = new byte[filestream.Length];
        //        filestream.Read(arr, 0, (int)filestream.Length);
        //        string base64 = Convert.ToBase64String(arr);
        //        return base64;
        //    }
        //}
        public static string GetFileContentAsBase64(string filePath)
        {
            // 只保留文件名,避免路径错误
            string fileName = Path.GetFileName(filePath);
 
            // 获取文件的完整路径
            string fullPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "image", fileName);
 
            if (!File.Exists(fullPath))
            {
                throw new FileNotFoundException("文件不存在:" + fullPath);
            }
 
            using (FileStream filestream = new FileStream(fullPath, FileMode.Open, FileAccess.Read))
            {
                byte[] arr = new byte[filestream.Length];
                filestream.Read(arr, 0, arr.Length);
                return Convert.ToBase64String(arr);
            }
        }
 
 
 
        /// <summary>
        /// 人脸注册
        /// </summary>
        /// <returns></returns>
        public static CreateUserResult AddUser(BDUserInfo info)
        {
            string token = GetAccessToken();
            var imgbase64 = GetFileContentAsBase64(info.ImgPath);
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "POST";
            request.KeepAlive = true;
            String str = "{\"image\":\"" + imgbase64 + "\",\"image_type\":\"BASE64\",\"group_id\":\"" + info.group_id + "\",\"user_id\":\"" + info.user_id + "\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}";
            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();
 
            NLog.LogManager.GetCurrentClassLogger().Trace("人脸注册:" + result);
            CreateUserResult res = JsonConvert.DeserializeObject<CreateUserResult>(result);//需要将log_id和face_token保存到用户表中,在人脸删除中需要用到
 
            return res;
        }
 
        /// <summary>
        /// 人脸删除(删除用户的某一张人脸,如果该用户只有一张人脸图片,则同时删除用户。)
        /// </summary>
        /// <returns></returns>
        public static string DeleteUserImg(DeleteUserImg info)
        {
            string token = GetAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/delete?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "POST";
            request.KeepAlive = true;
            String str = "{\"face_token\":\"" + info.face_token + "\",\"log_id\":\"" + info.log_id + "\",\"group_id\":\"" + info.group_id + "\",\"user_id\":\"" + info.user_id + "\"}";
            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();
 
            NLog.LogManager.GetCurrentClassLogger().Trace("人脸删除:" + result);
            return result;
        }
 
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <returns></returns>
        public static string DeleteUser(DeleteUserImg info)
        {
            string token = GetAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/delete?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "POST";
            request.KeepAlive = true;
            String str = "{\"group_id\":\"" + info.group_id + "\",\"user_id\":\"" + info.user_id + "\"}";
            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();
 
            NLog.LogManager.GetCurrentClassLogger().Trace("用户删除:" + result);
            return result;
        }
 
        /// <summary>
        /// 人脸搜索
        /// </summary>
        /// <returns></returns>
        public static SearchResult FaceSearch(string path, string group_id_list)
        {
            string token = GetAccessToken();
            var imgbase64 = GetFileContentAsBase64(path);
 
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "POST";
            request.KeepAlive = true;
            String str = "{\"image\":\"" + imgbase64 + "\",\"image_type\":\"BASE64\",\"group_id_list\":\"" + group_id_list + "\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}";
            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();
 
            NLog.LogManager.GetCurrentClassLogger().Trace("人脸搜索:" + result);
            SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result);
 
            return searchResult;
        }
        #endregion
 
    }
 
    
    /// <summary>
    /// token获取信息
    /// </summary>
    public class BDToken
    {
        /// <summary>
        /// 认证token
        /// </summary>
        public string access_token { get; set; }
        /// <summary>
        /// Access Token的有效期(秒为单位,有效期30天)
        /// </summary>
        public int expires_in { get; set; }
        /// <summary>
        /// 获取时间
        /// </summary>
        public string getdate { get; set; }
    }
 
    /// <summary>
    /// 人脸注册信息
    /// </summary>
    public class BDUserInfo
    {
        /// <summary>
        /// 图片路径(总数据大小应小于10M,分辨率应小于1920*1080)
        /// </summary>
        public string ImgPath { get; set; }
        /// <summary>
        /// 用户组id,标识一组用户(由数字、字母、下划线组成),长度限制48B
        /// </summary>
        public string group_id { get; set; }
        /// <summary>
        /// 用户id(由数字、字母、下划线组成),对应系统账号
        /// </summary>
        public string user_id { get; set; }
    }
    /// <summary>
    /// 人脸注册时返回对象
    /// </summary>
    public class CreateUserResult
    {
        /// <summary>
        /// 检索成功返回0
        /// </summary>
        public int error_code { get; set; }
        public string error_msg { get; set; }
        /// <summary>
        /// 请求标识码,随机数,唯一
        /// </summary>
        public string log_id {  get; set; }
        public CreateUser result { get; set; }
    }
    public class CreateUser
    {
        /// <summary>
        /// 人脸图片的唯一标识
        /// </summary>
        public string face_token {  get; set; }
    }
 
    /// <summary>
    /// 人脸搜索时返回的对象
    /// </summary>
    public class SearchResult
    {
        /// <summary>
        /// 检索成功返回0
        /// </summary>
        public int error_code { get; set; }
        public string error_msg { get; set;}
        public UserResult result { get; set;}
        
    }
    public class UserResult
    {
        public string face_token {  get; set; }
        public List<User_List> user_list { get; set;}
    }
    public class User_List
    {
        public string user_id { get; set; }
        /// <summary>
        /// 用户的匹配得分,80分以上可以判断为同一人
        /// </summary>
        public string score { get; set;}
    }
    /// <summary>
    /// 人脸删除的入参对象(只删除某一张图片,如果该用户只有一张图片,那该用户整体删除
    /// </summary>
    public class DeleteUserImg
    {
        /// <summary>
        /// 请求标识码,随机数,唯一
        /// </summary>
        public string log_id { get; set;}
        /// <summary>
        /// 用户id(由数字、字母、下划线组成),长度限制48B
        /// </summary>
        //public string user_id { get; set;}
        public string user_id { get; set;}
        /// <summary>
        /// 用户组id(由数字、字母、下划线组成) 长度限制48B,删除指定group_id中的user_id信息
        /// </summary>
        public string group_id { get; set;}
        /// <summary>
        /// 需要删除的人脸图片token,(由数字、字母、下划线组成)长度限制64B
        /// </summary>
        public string face_token { get; set;}
    }
}