.net 通过ImgUrl调用fcae++验证图片是否有人脸

.net 通过ImgUrl调用fcae++验证图片是否有人脸

face++官网:https://console.faceplusplus.com.cn/documents/4888373

官方api说明:

这里写图片描述

第一种方法:前台ajax直接请求(确定容易暴露apikey,按访问量收费啊,当然有加密的方式这里不做介绍了),废话不多说直接上代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script>
    $(document).ready(
        test()
    );


    function test() {
        $.ajax({
            //提交数据的类型 POST GET
            type: "POST",
            //提交的网址
            url: "https://api-cn.faceplusplus.com/facepp/v3/detect",
            //提交的数据
            data: {
                api_key: "自己买的就不告诉你们了(*^__^*) 嘻嘻……",
                api_secret: "自己买的就不告诉你们了(*^__^*) 嘻嘻……",
                image_url: "https://bj-mc-prod-asset.oss-cn-beijing.aliyuncs.com/mc-official/images/demo/demo-pic1.jpg",
                return_landmark: "1",
                return_attributes: "gender,age,smiling,headpose,facequality,blur,eyestatus,ethnicity,emotion"
            },
            //返回数据的格式
            datatype: "json", //"xml", "html", "script", "json", "jsonp", "text".
            //在请求之前调用的函数
            beforeSend: function () { $("#msg").html("logining"); },
            //成功返回之后调用的函数             
            success: function (data) {
                $("#msg").html(data);
            },
            //调用执行后调用的函数
            complete: function (XMLHttpRequest, textStatus) {
                alert(XMLHttpRequest.responseText);
                alert(textStatus);
                //HideLoading();
            },
            //调用出错执行的函数
            error: function () {
                //请求出错处理
            }
        });

    }
</script>

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="msg">

    </div>
    </form>
</body>
</html>

返回说明:
这里写图片描述

第二种方法:后台调用(WebRequest,可以做成webservice或者api 随你怎么折腾,我这里用webservice),上代码

namespace TestService.FaceWebService
{
    /// <summary>
    /// FaceCheckService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
    // [System.Web.Script.Services.ScriptService]
    public class FaceCheckService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        /// <summary>
        /// 根据前台传进来的URL验证图片是否有人脸
        /// 0:无
        /// 1:有
        /// </summary>
        /// <param name="imageUrl"></param>
        /// <returns></returns>
        [WebMethod]

        public int  FaceCheck(string imageUrl)
        {

            int reset = 0;

            try
            {
                var api_key = System.Configuration.ConfigurationManager.AppSettings["api_key"].ToString();
                var api_secret = System.Configuration.ConfigurationManager.AppSettings["api_secret"].ToString();
                var return_landmark = System.Configuration.ConfigurationManager.AppSettings["return_landmark"].ToString();
                var posturl = System.Configuration.ConfigurationManager.AppSettings["postfaceurl"].ToString();
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                IDictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("api_key", api_key); //调用此API的API Key
                parameters.Add("api_secret", api_secret); //调用此API的API Secret
                parameters.Add("image_url", imageUrl);
                parameters.Add("return_landmark", return_landmark);
                HttpWebResponse response = CreatePostHttpResponse(posturl, parameters, encoding);
                //打印返回值  
                Stream stream = response.GetResponseStream();   //获取响应的字符串流  
                StreamReader sr = new StreamReader(stream); //创建一个stream读取流  
                string html = sr.ReadToEnd();   //从头读到尾,放到字符串html
                //序列化face++人脸验证的匿名对象
                var svcResult = Brick.Common.Serialization.JavaScriptHelper.Deserialize<FaceEntity>(html);//这里序列化用你们自己的
                if (svcResult.IsNotNull())
                {
                    reset = svcResult.faces.Length;
                }
            }
            catch (Exception ex)
            {
                reset = 0;
                Log.Error(string.Format("error-{0},StackTrace--{1}", ex.Message, ex.StackTrace));
            }

            return reset;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受     
        }

        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, Encoding charset)
        {
            HttpWebRequest request = null;
            //HTTPSQ请求  
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            request = WebRequest.Create(url) as HttpWebRequest;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Method = "POST";
            request.Accept = "*/*";
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0";
            //如果需要POST数据     
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = charset.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }    


    }
}

反序列化对象

namespace TestService.FaceWebService
{

    /// <summary>
    /// 返回值说明
    /// </summary>
    public class FaceEntity
    {
        public string request_id { get; set; }
        public Object[]faces { get; set; }
        public string image_id { get; set; }
        public string time_used { get; set; }
        public string error_message { get; set; }
    }


}

序列化(怎么用我想应该知道吧):

Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonString)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Jsoup获取图片,可以按照以下步骤进行操作: 1. 使用Jsoup.connect()方法连接到指定的URL。 2. 使用Jsoup.parse()方法解析HTML文档。 3. 使用doc.select()方法选择包含图片的元素。 4. 使用element.attr()方法获取图片URL。 5. 使用Jsoup.connect()方法连接到图片URL。 6. 使用Response.bodyAsBytes()方法获取图片的字节数组。 下面是一个示例代码,可以获取指定网页中的所有图片: ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.jsoup.Connection.Response; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class ImageDownloader { public static void main(String[] args) throws IOException { String url = "https://www.example.com"; Document doc = Jsoup.connect(url).get(); Elements imgs = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]"); for (Element img : imgs) { String imgUrl = img.attr("abs:src"); Response resultImageResponse = Jsoup.connect(imgUrl) .ignoreContentType(true).execute(); InputStream inputStream = resultImageResponse.bodyStream(); OutputStream outputStream = new FileOutputStream( "image_" + System.currentTimeMillis() + ".jpg"); int bytesRead = -1; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值