Unity对接图片审核SDK,亚马逊图片审核 AWSSDK.Rekognition 的RekognitionService.DetectModerationLabels图片审核C#版本示例---控制台

2022/7/9 1:20:37

本文主要是介绍Unity对接图片审核SDK,亚马逊图片审核 AWSSDK.Rekognition 的RekognitionService.DetectModerationLabels图片审核C#版本示例---控制台,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

因为亚马逊给的AWS Mobile SDK For Unity 中没有AWSSDK.Rekognition Service,没有图片审核的功能提供,而下载AWSSDK.Rekognition的donet的开发工具包,所对应的AWSSDK.Core又和AWS Mobile SDK For Unity的AWSSDK.Core冲突了,并且AWSSDK.Rekognition.dll所依赖的AWSSDK.Core的最低版本也比AWS Mobile SDK For Unity的AWSSDK.Core的版本高!啊这,这就比较无奈了。而走HTTP API的话,官方示例给出的又是Python语言的示例,所以这里进行了一个转义Pytho--->C#===>亚马逊图片审核AWSSDK.Rekognition的RekognitionService.DetectModerationLabels图片审核C#版本

呃,博客园没有缩进的嘛,这里面也有一个比较复杂的HTTP协议的构建和发送,可以学到一点东西。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
string access_key = "你的key,也就是AWS_ACCESS_KEY_ID";
string secret_key = "你的密钥,也就是AWS_ACCESS_SECRET";

string host = "rekognition.us-east-1.amazonaws.com";
string endpoint = "https://rekognition.us-east-1.amazonaws.com";
string service = "rekognition";
string method = "POST";
string region = "us-east-1";
string amz_target = "RekognitionService.DetectModerationLabels";
string content_type = "application/x-amz-json-1.1";


string amz_date = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ");
string date_stamp = DateTime.UtcNow.ToString("yyyyMMdd");
Console.WriteLine("amz_date===>"+amz_date);
Console.WriteLine("amz_stamp===>"+date_stamp);

string canonical_uri = "/";
string canonical_querystring = "";
string canonical_headers = "content-type:" + content_type + "\n" + "host:" + host + "\n" + "x-amz-date:" + amz_date + "\n" + "x-amz-target:" + amz_target + "\n";
string signed_headers = "content-type;host;x-amz-date;x-amz-target";

FileStream fileStream = new FileStream("D:/LK/aws-sdk-unity_3.3.802.0/source.jpg", FileMode.Open);
byte[] data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
fileStream.Close();

string pictureStr = Convert.ToBase64String(data);

string request_parameters = "{";
request_parameters += "\"Image\": {\"Bytes\": \"" + pictureStr + "\"}";
request_parameters += "}";


Console.WriteLine("payload_hash===BeforeHash===>"+ request_parameters);
var kha2 = HashAlgorithm.Create("SHA-256");
byte[] payload_hash_byte = kha2.ComputeHash(Encoding.UTF8.GetBytes(request_parameters));
string payload_hash_str = ToHexString(payload_hash_byte, true);
Console.WriteLine("payload_hash===AfterHash===>"+ payload_hash_str);
string helloworld = "helloworld";
var kha3 = HashAlgorithm.Create("SHA-256");
byte[] helloworld_byte = kha3.ComputeHash(Encoding.UTF8.GetBytes(helloworld));
string helloworld_str = ToHexString(helloworld_byte, true);
Console.WriteLine("helloworld===AfterHash===>" + helloworld_str);
string canonical_request = method + "\n" + canonical_uri + "\n" + canonical_querystring + "\n" + canonical_headers + "\n" + signed_headers + "\n" + payload_hash_str;
string algorithm = "AWS4-HMAC-SHA256";
string credential_scope = date_stamp + "/" + region + "/" + service + "/" + "aws4_request";
Console.WriteLine("canonical_request===BeforeHash===>" + canonical_request);
var kha1 = HashAlgorithm.Create("SHA-256");
byte[] canonical_request_byte = kha1.ComputeHash(Encoding.UTF8.GetBytes(canonical_request.ToString()));
string canonical_request_str = ToHexString(canonical_request_byte, true);
Console.WriteLine("canonical_request===AfterHash===>" + canonical_request_str);
string string_to_sign = algorithm + "\n" + amz_date + "\n" + credential_scope + "\n" + canonical_request_str;

var kha = KeyedHashAlgorithm.Create("HMACSHA256");
kha.Key = DeriveSigningKey("HMACSHA256", secret_key, region, date_stamp, service);
var signature = kha.ComputeHash(Encoding.UTF8.GetBytes(string_to_sign.ToString()));
var signatureString = ToHexString(signature, true);
Console.WriteLine("signature===>" + signatureString);
string authorization_header = algorithm + " " + "Credential=" + access_key + "/" + credential_scope + ", " + "SignedHeaders=" + signed_headers + ", " + "Signature=" + signatureString;

try
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = (HttpWebRequest)WebRequest.Create(new Uri(endpoint));
request.ServicePoint.Expect100Continue = false;
request.Method = method;
request.Host = host;
request.ContentType = content_type;
request.Headers.Add("x-amz-date", amz_date);
request.Headers.Add("x-amz-target", amz_target);

request.Headers.Add(HttpRequestHeader.Authorization, authorization_header);
Console.WriteLine("authorization_header===>" + authorization_header);

var buffer = new byte[8192]; // arbitrary buffer size
var requestStream = request.GetRequestStream();
using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(request_parameters)))
{
var bytesRead = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
request.ContentLength = inputStream.Length;
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("\n-- HTTP call succeeded");
var responseBody = ReadResponseBody(response);
if (!string.IsNullOrEmpty(responseBody))
{
Console.WriteLine("\n-- Response body:");
Console.WriteLine(responseBody);
}
}
else
Console.WriteLine("\n-- HTTP call failed, status code: {0}", response.StatusCode);
}
}
catch(WebException e)
{
using (var response = e.Response as HttpWebResponse)
{
if (response != null)
{
var errorMsg = ReadResponseBody(response);
Console.WriteLine("\n-- HTTP call failed with exception '{0}', status code '{1}'", errorMsg, response.StatusCode);
}
}
}

}

public static byte[] DeriveSigningKey(string algorithm, string awsSecretAccessKey, string region, string date, string service)
{
const string ksecretPrefix = "AWS4";
char[] ksecret = null;

ksecret = (ksecretPrefix + awsSecretAccessKey).ToCharArray();

byte[] hashDate = ComputeKeyedHash(algorithm, Encoding.UTF8.GetBytes(ksecret), Encoding.UTF8.GetBytes(date));
byte[] hashRegion = ComputeKeyedHash(algorithm, hashDate, Encoding.UTF8.GetBytes(region));
byte[] hashService = ComputeKeyedHash(algorithm, hashRegion, Encoding.UTF8.GetBytes(service));
return ComputeKeyedHash(algorithm, hashService, Encoding.UTF8.GetBytes("aws4_request"));
}

public static byte[] ComputeKeyedHash(string algorithm, byte[] key, byte[] data)
{
var kha = KeyedHashAlgorithm.Create(algorithm);
kha.Key = key;
return kha.ComputeHash(data);
}

public static string ToHexString(byte[] data, bool lowercase)
{
var sb = new StringBuilder();
for (var i = 0; i < data.Length; i++)
{
sb.Append(data[i].ToString(lowercase ? "x2" : "X2"));
}
return sb.ToString();
}

public static string ReadResponseBody(HttpWebResponse response)
{
if (response == null)
throw new ArgumentNullException("response", "Value cannot be null");

// Then, open up a reader to the response and read the contents to a string
// and return that to the caller.
string responseBody = string.Empty;
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseBody = reader.ReadToEnd();
}
}
}
return responseBody;
}
}
}



这篇关于Unity对接图片审核SDK,亚马逊图片审核 AWSSDK.Rekognition 的RekognitionService.DetectModerationLabels图片审核C#版本示例---控制台的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程