人脸识别- 接入face++api

人脸识别- 接入face++api


public class MainActivity extends AppCompatActivity {
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();
    /**
     * 缓存目录
     */
    public static final String CACHEPATH = Environment
            .getExternalStorageDirectory() + "/facetest/.cache/";
    private static final int REQUEST_CODE_SELECT_PIC = 1050;
    private ImageView imageView1,imageView2;
    private TextView textView;
    private File file;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1){
                textView.setText(msg.obj+"");
            }else if (msg.what == 2){
                //选择的图片不是头像
                Toast.makeText(MainActivity.this,"选择的图片不是头像o",Toast.LENGTH_SHORT).show();
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView1 = (ImageView) findViewById(R.id.iv_image1);
        imageView2 = (ImageView) findViewById(R.id.iv_image2);
        textView = (TextView) findViewById(R.id.tv_msg);
    }


    private void choosePic() {
//可以使用你自己的图片选择器(支持拍照和相册选取),这边用了第三方imageselecter库
        ImageConfig imageConfig
                = new ImageConfig.Builder(new GlideLoader())
                //.steepToolBarColor(ToolUtils.setColor(PersonActivity.this,R.color.bg_color))
                // .titleBgColor(ToolUtils.setColor(PersonActivity.this,R.color.main_color))
                //.titleSubmitTextColor(ToolUtils.setColor(PersonActivity.this,R.color.white))
                //.titleTextColor(ToolUtils.setColor(PersonActivity.this,R.color.white))
                // 开启单选   (默认为多选)
                .singleSelect()
                // 开启拍照功能 (默认关闭)
                .showCamera()
                // 拍照后存放的图片路径
                .filePath(CACHEPATH)
                .crop()
                .requestCode(REQUEST_CODE_SELECT_PIC)
                .build();
        ImageSelector.open(this, imageConfig);   // 开启图片选择器
    }


    private int one;
    public void btnOnClick(View view){
        switch (view.getId()){
            case R.id.one:
                one = 1;
                choosePic();
                break;
            case R.id.two:
                one = 2;
                choosePic();
                break;
            case R.id.compare:
                one = 3;
                if (TextUtils.isEmpty(face_token1) || TextUtils.isEmpty(face_token2)){
                    Toast.makeText(MainActivity.this,"请选择图片",Toast.LENGTH_SHORT).show();
                    return;
                }
                new myThread3().start();
                break;
            default:
                break;
        }


    }
    private String face_token1 , face_token2;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_SELECT_PIC) {
                List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                String url = pathList.get(0);


                file = new File(url);
                Log.d("更改头像--path", url);
                if (one == 1){
                    imageView1.setImageBitmap(BitmapFactory.decodeFile(url));
                    new myThread1().start();
                }else if (one == 2){
                    imageView2.setImageBitmap(BitmapFactory.decodeFile(url));
                    new myThread2().start();
                }
            }
        }
    }
    class myThread1 extends Thread{
        @Override
        public void run() {
            super.run();
            check(file);
        }
    }


    class myThread2 extends Thread{
        @Override
        public void run() {
            super.run();
            check(file);
        }
    }


    class myThread3 extends Thread{
        @Override
        public void run() {
            super.run();
            compare();
        }
    }
/**---------------------人脸识别 start----------------------------------*/
    /**
     * 人脸识别
     * @param file
     */
    private void check(File file) {
        byte[] buff = getBytesFromFile(file);
        String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, byte[]> byteMap = new HashMap<>();
        map.put("api_key", "XFzCl8KJkgoYhF_8_zfyVgOMGcLN4Tug");
        map.put("api_secret", "BKTytJPMzpZSv30VtnzO-gwyvMBtHS8z");
        byteMap.put("image_file", buff);
        try{
            byte[] bacd = post(url, map, byteMap);
            String str = new String(bacd);
            Log.d("人脸检测--str", str);
            // face_token1 =
            FaceImageData data = JSONObject.parseObject(str,FaceImageData.class);
            if (data.getFaces() != null && data.getFaces().size() != 0){
                if (one == 1){
                    face_token1 = data.getFaces().get(0).getFace_token();
                }else {
                    face_token2 = data.getFaces().get(0).getFace_token();
                }
            }else {
                //选择的图片不是头像
                Message message = handler.obtainMessage();
                message.what = 2;
                handler.sendMessage(message);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }


    }




    protected static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while(iter.hasNext()){
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if(fileMap != null && fileMap.size() > 0){
            Iterator fileIter = fileMap.entrySet().iterator();
            while(fileIter.hasNext()){
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try{
            if(code == 200){
                ins = conne.getInputStream();
            }else{
                ins = conne.getErrorStream();
            }
        }catch (SSLException e){
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while((len = ins.read(buff)) != -1){
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }
    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }
    private static String encode(String value) throws Exception{
        return URLEncoder.encode(value, "UTF-8");
    }


    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }


/**---------------------人脸识别 end-----------------------------------------*/
    /**---------------------人脸比对 start-----------------------------------------*/


    private void compare() {
        String url = "https://api-cn.faceplusplus.com/facepp/v3/compare";
        HashMap<String, String> map = new HashMap<>();
        map.put("api_key", "XFzCl8KJkgoYhF_8_zfyVgOMGcLN4Tug");
        map.put("api_secret", "BKTytJPMzpZSv30VtnzO-gwyvMBtHS8z");
        map.put("face_token1", face_token1);
        map.put("face_token2", face_token2);
        try{
            byte[] bacd = post(url, map, null);
            String str = new String(bacd);
            Log.d("人脸比对--str", str);
            Message message = handler.obtainMessage();
            message.what = 1;
            message.obj = str;
            handler.sendMessage(message);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }










    /**---------------------人脸比对 end-----------------------------------------*/
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值