腾讯云图片鉴黄集成到C#

腾讯云图片鉴黄集成到C#官方文档:https://cloud.tencent.com/document/product/641/12422请求官方API及签名的生成代码如下:varurlList=newList<string>();urlList.Add(url);//请求参数…

官方文档:https://cloud.tencent.com/document/product/641/12422

请求官方API及签名的生成代码如下:

 

            var urlList = new List<string>();
            urlList.Add(url);
            //请求参数
            var req = new { appid = ConfigurationManager.AppSettings["AppId"], url_list = urlList };
            var psotJson = JsonConvert.SerializeObject(req);

            TencentCloundPicHelper tencentHelper = new TencentCloundPicHelper();
            var info = tencentHelper.SendPost(psotJson);
            TencentJianHuangResponse response = JsonConvert.DeserializeObject<TencentJianHuangResponse>(info);

            if (response != null && response.result_list.Any())
            {
                if (response.result_list.FirstOrDefault().code == 0)//成功
                {
                    if (response.result_list.FirstOrDefault().data.result != 0)//是黄图
                    {
                        responseMessage.Message = CommonConst.PicNolegal;
                        responseMessage.ResultCode = "555";
                        responseMessage.Info = new { Url = url, TencentJson = info };
                        return responseMessage;
                    }
                }
            }

 

 

    public class TencentJianHuangResponse
    {
        public List<ImgInfo> result_list = new List<ImgInfo>();
    }

    public class ImgInfo{

        /// <summary>
        /// 错误码,0 为成功
        /// </summary>
        public int code { set; get; }

        /// <summary>
        /// 服务器返回的信息
        /// </summary>
        public string message { set; get; }

        /// <summary>
        /// 当前图片的 url
        /// </summary>
        public string url { set; get; }

        /// <summary>
        /// 具体查询数据,具体见实体
        /// </summary>
        public Data data;
    }

    public class Data
    {
        /// <summary>
        /// 0 正常,1 黄图,2 疑似图片
        /// </summary>
        public int result { set; get; }

        /// <summary>
        /// 封禁状态,0 表示正常,1 表示图片已被封禁(只有存储在腾讯云的图片才会被封禁)
        /// </summary>
        public int forbid_status { set; get; }

        /// <summary>
        /// 识别为黄图的置信度,分值 0-100;是 normal_score , hot_score , porn_score的综合评分
        /// </summary>
        public decimal confidence { set; get; }

        /// <summary>
        /// 图片为正常图片的评分
        /// </summary>
        public decimal hot_score { set; get; }

        /// <summary>
        /// 图片为性感图片的评分
        /// </summary>
        public decimal normal_score { set; get; }

        /// <summary>
        /// 图片为色情图片的评分
        /// </summary>
        public decimal porn_score { set; get; }
    }

 

    public class TencentCloundPicHelper
    {
        /// <summary>
        /// 发送Post请求腾讯云
        /// </summary>
        public string SendPost(string postDataStr)
        {
            var url = @"http://service.image.myqcloud.com/detection/porn_detect";

            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;
                var request = (HttpWebRequest)HttpWebRequest.Create(url);
                
                request.Method = "POST";
                
                SetHeaderValue(request.Headers, "content-type", "application/json");
                SetHeaderValue(request.Headers, "content-length", postDataStr.Length.ToString());
                SetHeaderValue(request.Headers, "Host", "service.image.myqcloud.com");
                SetHeaderValue(request.Headers, "authorization", GetSign());
                var memStream = new MemoryStream();
                
                var jsonByte = Encoding.GetEncoding("utf-8").GetBytes(postDataStr);
                memStream.Write(jsonByte, 0, jsonByte.Length);

                request.ContentLength = memStream.Length;
                var requestStream = request.GetRequestStream();
                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();

                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                var response = request.GetResponse();
                using (var s = response.GetResponseStream())
                {
                    var reader = new StreamReader(s, Encoding.UTF8);
                    return reader.ReadToEnd();
                }
            }
            catch (WebException we)
            {
                if (we.Status == WebExceptionStatus.ProtocolError)
                {
                    using (var s = we.Response.GetResponseStream())
                    {
                        var reader = new StreamReader(s, Encoding.UTF8);
                        return reader.ReadToEnd();
                    }
                }
                else
                {
                    throw we;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 获取签名
        /// </summary>
        public static string GetSign()
        {
            var appId = ConfigurationManager.AppSettings["AppId"];//开发者的 APPID,接入智能图像时由系统生成
            var bucket = "tengxunyun";//Bucket,空间名称,即图片资源的组织管理单元
            var secretId = ConfigurationManager.AppSettings["SecretId"];//Secret ID
            var secretKey = ConfigurationManager.AppSettings["SecretKey"];//secretKey
            var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            var currentTime = Convert.ToInt64(ts.TotalSeconds);//当前时间戳,是一个符合 UNIX Epoch 时间戳规范的数值,单位为秒,多次签名时,e 应大于 t
            var expiredTime = Convert.ToInt64((DateTime.UtcNow.AddMinutes(180) - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);//签名的有效期,是一个符合 UNIX Epoch 时间戳规范的数值,单位为秒;单次签名时,e 必须设置为 0
            var rand = GetRandom();//随机串,无符号 10 进制整数,用户需自行生成,最长 10 位
            var userid = 0;//历史遗留字段,请填写为 0
            var fileid = "";//资源存储的唯一标识,单次签名必填;多次签名选填,如填写则会验证与当前操作的文件路径是否一致。
            var encryptText = $"a={appId}&b={bucket}&k={secretId}&e={expiredTime}&t={currentTime}&r={rand}&u=0&f=";
            var sign = Hmacsha1Encrypt(encryptText, secretKey);

            return sign;
        }

        /// <summary>
        /// 设置Http post请求头
        /// </summary>
        public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
        {
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(header, null) as NameValueCollection;
                collection[name] = value;
            }
        }

        /// <summary>
        /// HMACSHA1算法加密
        /// </summary>
        private static string Hmacsha1Encrypt(string encryptText, string encryptKey)
        {
            using (HMACSHA1 mac = new HMACSHA1(Encoding.UTF8.GetBytes(encryptKey)))
            {
                var hash = mac.ComputeHash(Encoding.UTF8.GetBytes(encryptText));
                var pText = Encoding.UTF8.GetBytes(encryptText);
                var all = new byte[hash.Length + pText.Length];
                Array.Copy(hash, 0, all, 0, hash.Length);
                Array.Copy(pText, 0, all, hash.Length, pText.Length);
                return Convert.ToBase64String(all);
            }
        }

        /// <summary>
        /// 获取随机数
        /// </summary>
        private static int GetRandom()
        {
            var random = new Random();
            var rand = random.Next(10000, 999999999);
            return rand;
        }
    }

 

转载于:https://www.cnblogs.com/dawenyang/p/9019264.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/38376.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注