腾讯云图片鉴黄集成到C#
2024-10-24 22:52:32
官方文档: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 == )//成功
{
if (response.result_list.FirstOrDefault().data.result != )//是黄图
{
responseMessage.Message = CommonConst.PicNolegal;
responseMessage.ResultCode = "";
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, , jsonByte.Length); request.ContentLength = memStream.Length;
var requestStream = request.GetRequestStream();
memStream.Position = ;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, , tempBuffer.Length);
memStream.Close(); requestStream.Write(tempBuffer, , 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(, , , , , , );
var currentTime = Convert.ToInt64(ts.TotalSeconds);//当前时间戳,是一个符合 UNIX Epoch 时间戳规范的数值,单位为秒,多次签名时,e 应大于 t
var expiredTime = Convert.ToInt64((DateTime.UtcNow.AddMinutes() - new DateTime(, , , , , , )).TotalSeconds);//签名的有效期,是一个符合 UNIX Epoch 时间戳规范的数值,单位为秒;单次签名时,e 必须设置为 0
var rand = GetRandom();//随机串,无符号 10 进制整数,用户需自行生成,最长 10 位
var userid = ;//历史遗留字段,请填写为 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, , all, , hash.Length);
Array.Copy(pText, , all, hash.Length, pText.Length);
return Convert.ToBase64String(all);
}
} /// <summary>
/// 获取随机数
/// </summary>
private static int GetRandom()
{
var random = new Random();
var rand = random.Next(, );
return rand;
}
}
最新文章
- HTML2
- 让keepalived监控NginX的状态
- 【转】Centos配置yum源
- in on at 总结
- java新手笔记9 类的封装示例
- system()、exec()、fork()三个与进程有关的函数的比较
- c#Socket服务器与客户端的开发(2)
- python标准库总的random函数用法
- C++回顾day02---<;拷贝构造函数:重点>;
- 三种方法获取Class对象的区别
- Servlet中(Session、cookies、servletcontext)的基本用法
- cuda中用cublas库做矩阵乘法
- 解决 idea 中的 tomcat控制台 和cmd tomcat下的中文乱码问题(win10 64位)
- 【loj2639】[Tjoi2017]不勤劳的图书管理员
- windows accounts
- unity statics window fps原理
- centos7 安装 mysql-python时 报错 EnvironmentError: mysql_config not found
- kernel下制作动态logo
- rtems 4.11 RTC驱动 (arm, beagle)
- JavaScript禁止键入非法值,只有这些才能被键入