package com.example.buyishi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HTTPRequest {

    private final String url;
    private final int timeout;
    private final StringBuilder params;

    public HTTPRequest(String url, int timeout) throws IOException {
        this.url = url;
        this.timeout = timeout;
        params = new StringBuilder();
    }

    public HTTPRequest addParam(String name, String value) {
        params.append(name).append('=').append(value).append('&');
        return this;
    }

    public HTTPRequest clearParams() {
        params.delete(0, params.length());
        return this;
    }

    public String get() throws IOException {
        URLConnection connection = new URL(url + '?' + params).openConnection();
        return readFromURLConnection(connection);
    }

    public String post() throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.getOutputStream().write(params.toString().getBytes("UTF-8"));
        return readFromURLConnection(connection);
    }

    private String readFromURLConnection(URLConnection connection) throws IOException {
        connection.setConnectTimeout(timeout);
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = br.readLine()) != null) {
            response.append(line);
        }
        return response.toString();
    }
}
package com.example.buyishi;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MainFrame extends JFrame {

    private TooltipImageLabel imgLabel1, imgLabel2;
    private JButton compareButton;
    private JTextField similarityTextField;
    private File picFile1, picFile2;
    private static final String APP_ID = "f89ae61fd63d4a63842277e9144a6bd2";
    private static final String APP_KEY = "af1cd33549c54b27ae24aeb041865da2";

    public MainFrame() {
        super("EyeKey Demo");
        initFrame();
    }

    private void initFrame() {
        setSize(850, 650);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout(0, 20));
        imgLabel1 = new TooltipImageLabel("Picture1", TooltipImageLabel.CENTER);
        imgLabel1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        imgLabel1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                PicFileChooser fileChooser = new PicFileChooser();
                if (PicFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(MainFrame.this)) {
                    picFile1 = fileChooser.getSelectedFile();
                    imgLabel1.setImage(picFile1);
                    similarityTextField.setText(null);
                }
            }
        });
        imgLabel2 = new TooltipImageLabel("Picture2", TooltipImageLabel.CENTER);
        imgLabel2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        imgLabel2.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                PicFileChooser fileChooser = new PicFileChooser();
                if (PicFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(MainFrame.this)) {
                    picFile2 = fileChooser.getSelectedFile();
                    imgLabel2.setImage(picFile2);
                    similarityTextField.setText(null);
                }
            }
        });
        JPanel labelPanel = new JPanel(new GridLayout(1, 2, 20, 0));
        labelPanel.add(imgLabel1);
        labelPanel.add(imgLabel2);
        add(labelPanel);
        compareButton = new JButton("Compare");
        compareButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (picFile1 == null || picFile2 == null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "Please choose pic files you want to compare!", "Tip", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    try (FileInputStream fis1 = new FileInputStream(picFile1); FileInputStream fis2 = new FileInputStream(picFile2)) {
                        String picBase64 = getFileBase64(fis1);
                        HTTPRequest httpRequest = new HTTPRequest("https://api.eyekey.com/face/Check/checking/", 1000);
                        httpRequest.addParam("app_id", APP_ID).addParam("app_key", APP_KEY).addParam("img", URLEncoder.encode(picBase64, "UTF-8"));
                        JsonParser jsonParser = new JsonParser();
                        JsonObject jsonObject = jsonParser.parse(httpRequest.post()).getAsJsonObject();
                        if (jsonObject.get("res_code").getAsString().equals("0000")) {
                            String faceId1 = jsonObject.getAsJsonArray("face").get(0).getAsJsonObject().get("face_id").getAsString();
                            picBase64 = getFileBase64(fis2);
                            httpRequest.clearParams().addParam("app_id", APP_ID).addParam("app_key", APP_KEY).addParam("img", URLEncoder.encode(picBase64, "UTF-8"));
                            jsonObject = jsonParser.parse(httpRequest.post()).getAsJsonObject();
                            if (jsonObject.get("res_code").getAsString().equals("0000")) {
                                String faceId2 = jsonObject.getAsJsonArray("face").get(0).getAsJsonObject().get("face_id").getAsString();
                                httpRequest = new HTTPRequest("https://api.eyekey.com/face/Match/match_compare/", 1000);
                                httpRequest.addParam("app_id", APP_ID).addParam("app_key", APP_KEY).addParam("face_id1", faceId1).addParam("face_id2", faceId2);
                                jsonObject = jsonParser.parse(httpRequest.get()).getAsJsonObject();
                                if (jsonObject.get("res_code").getAsString().equals("0000")) {
                                    similarityTextField.setText("Similarity: " + jsonObject.get("similarity").getAsFloat());
                                } else
                                    JOptionPane.showMessageDialog(MainFrame.this, jsonObject.get("message"), "Error", JOptionPane.ERROR_MESSAGE);
                            } else {
                                JOptionPane.showMessageDialog(MainFrame.this, jsonObject.get("message"), "Error: Pic2", JOptionPane.ERROR_MESSAGE);
                            }
                        } else {
                            JOptionPane.showMessageDialog(MainFrame.this, jsonObject.get("message"), "Error: Pic1", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                        JOptionPane.showMessageDialog(MainFrame.this, "Error Information:\n" + ex, "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        JPanel southPanel = new JPanel(new GridLayout(2, 1, 0, 20));
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(compareButton);
        southPanel.add(buttonPanel);
        similarityTextField = new JTextField();
        similarityTextField.setForeground(Color.RED);
        similarityTextField.setEditable(false);
        similarityTextField.setHorizontalAlignment(JTextField.CENTER);
        southPanel.add(similarityTextField);
        add(southPanel, "South");
    }

    private String getFileBase64(FileInputStream fis) throws IOException {
        byte[] src = new byte[fis.available()];
        fis.read(src);
        return Base64.getEncoder().encodeToString(src);
    }

    public static void main(String[] args) {
        new MainFrame().setVisible(true);
    }
}
package com.example.buyishi;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class PicFileChooser extends JFileChooser {

    public PicFileChooser() {
        initFileFilter();
    }

    private void initFileFilter() {
        FileNameExtensionFilter filter1 = new FileNameExtensionFilter("All Picture Files", "ico", "png", "tif", "tiff", "gif", "jpg", "jpeg", "jpe", "jfif", "bmp", "dib");
        FileNameExtensionFilter filter2 = new FileNameExtensionFilter("ICO (*.ico)", "ico");
        FileNameExtensionFilter filter3 = new FileNameExtensionFilter("PNG (*.png)", "png");
        FileNameExtensionFilter filter4 = new FileNameExtensionFilter("TIFF (*.tif;*.tiff)", "tif", "tiff");
        FileNameExtensionFilter filter5 = new FileNameExtensionFilter("GIF (*.gif)", "gif");
        FileNameExtensionFilter filter6 = new FileNameExtensionFilter("JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)", "jpg", "jpeg", "jpe", "jfif");
        FileNameExtensionFilter filter7 = new FileNameExtensionFilter("Bitmap Files (*.bmp)", "bmp", "dib");
        setFileFilter(filter1);
        setFileFilter(filter2);
        setFileFilter(filter3);
        setFileFilter(filter4);
        setFileFilter(filter5);
        setFileFilter(filter6);
        setFileFilter(filter7);
    }
}
package com.example.buyishi;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class TooltipImageLabel extends JLabel {

    private JFrame tooltipFrame;
    private JLabel tooltipLabel;
    private boolean imageSetted;
    private int mouseX, mouseY;

    public TooltipImageLabel(String text, int horizontalAlignment) {
        super(text, horizontalAlignment);
        initComponents();
        initListeners();
    }

    public void setImage(File imgFile) {
        try {
            BufferedImage sourceImage = ImageIO.read(imgFile);
            int sourceWidth = sourceImage.getWidth(), sourceHeight = sourceImage.getHeight();
            int labelWidth = getWidth(), labelHeight = getHeight();
            setText(null);
            String tooltip = imgFile.getAbsolutePath();
            tooltipLabel.setText(tooltip);
            tooltipFrame.setSize(tooltip.length() * 8, 30);
            if (sourceWidth > labelWidth || sourceHeight > labelHeight) {
                float sourceScale = (float) sourceWidth / sourceHeight, labelScale = (float) labelWidth / labelHeight;
                int targetWidth, targetHeight;
                if (labelScale < sourceScale) {
                    targetWidth = getWidth();
                    targetHeight = (int) (targetWidth / sourceScale + 0.5);
                } else {
                    targetHeight = getHeight();
                    targetWidth = (int) (sourceScale * targetHeight);
                }
                setIcon(new ImageIcon(sourceImage.getScaledInstance(targetWidth, targetHeight, BufferedImage.SCALE_DEFAULT)));
            } else {
                setIcon(new ImageIcon(sourceImage));
            }
            imageSetted = true;
        } catch (IOException ex) {
            Logger.getLogger(TooltipImageLabel.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Error Information:\n" + ex, "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void initComponents() {
        setOpaque(true);
        setBackground(Color.WHITE);
        tooltipFrame = new JFrame();
        tooltipFrame.setUndecorated(true);
        tooltipFrame.getContentPane().setBackground(new Color(242, 246, 249));
        tooltipLabel = new JLabel();
        tooltipLabel.setForeground(new Color(127, 157, 203));
        tooltipFrame.add(tooltipLabel);
    }

    private void initListeners() {
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                if (imageSetted) {
                    int currentX = e.getXOnScreen(), currentY = e.getYOnScreen();
                    if (Math.abs(currentX - mouseX) > 10 || Math.abs(currentY - mouseY) > 10) {
                        tooltipFrame.setLocation(currentX, currentY + 20);
                        if (!tooltipFrame.isVisible())
                            tooltipFrame.setVisible(true);
                        mouseX = currentX;
                        mouseY = currentY;
                    }
                }
            }
        });
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                if (imageSetted) {
                    mouseX = e.getXOnScreen();
                    mouseY = e.getYOnScreen();
                    tooltipFrame.setLocation(mouseX, mouseY + 20);
                    tooltipFrame.setVisible(true);
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                if (tooltipFrame.isVisible()) {
                    tooltipFrame.dispose();
                }
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                if (tooltipFrame.isVisible()) {
                    tooltipFrame.dispose();
                }
            }
        });
    }
}

Java客户端:调用EyeKey HTTP接口进行人脸对比的更多相关文章

  1. Java与WCF交互(一):Java客户端调用WCF服务

    最近开始了解WCF,写了个最简单的Helloworld,想通过java客户端实现通信.没想到以我的基础,居然花了整整两天(当然是工作以外的时间,呵呵),整个过程大费周折,特写下此文,以供有需要的朋友参 ...

  2. java如何调用对方http接口(II)

    java如何调用接口 在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适,所以,问题来了,java如何调用接口?很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对 ...

  3. Java与WCF交互(一):Java客户端调用WCF服务 【转】

    原文:http://www.cnblogs.com/downmoon/archive/2010/08/24/1807161.html 最近开始了解WCF,写了个最简单的Helloworld,想通过ja ...

  4. 转载——Java与WCF交互(一):Java客户端调用WCF服务

    最近开始了解WCF,写了个最简单的Helloworld,想通过java客户端实现通信.没想到以我的基础,居然花了整整两天(当然是工作以外的时间,呵呵),整个过程大费周折,特写下此文,以供有需要的朋友参 ...

  5. 使用java客户端调用redis

    Redis支持很多编程语言的客户端,有C.C#.C++.Clojure.Common Lisp.Erlang.Go.Lua.Objective-C.PHP.Ruby.Scala,甚至更时髦的Node. ...

  6. java客户端调用ftp上传下载文件

    1:java客户端上传,下载文件. package com.li.utils; import java.io.File; import java.io.FileInputStream; import ...

  7. Java 常调用的Webservice接口的方法

    WebService是基于Web的服务,WebService使用SOAP协议实现跨编程语言和跨操作系统平台,接收和响应外部系统的某种请求,从而实现远程调用.WebService采用HTTP协议传输数据 ...

  8. Java客户端调用.NET的WebService

    项目需要去调用.NET的WebSrevice,本身是Java,研究了半天,终于有些头绪,记下来. 1,新建.NET WebService.只在原方法上加上一个string类型的参数str [WebMe ...

  9. java客户端调用c#的webservice服务

    此处使用到了CXF框架,可以使用以下坐标从maven仓库中获取相关jar包: <dependency> <groupId>org.apache.cxf</groupId& ...

随机推荐

  1. nginx的详解(三)

    6.禁止访问某个文件或目录1)禁止访问以txt或doc结尾的文件location ~* \.(txt|doc)${root /data/www/wwwroot/linuxtone/test;deny ...

  2. BZOJ 2829 信用卡凸包 ——计算几何

    凸包裸题 #include <map> #include <cmath> #include <queue> #include <cstdio> #inc ...

  3. BZOJ 1778 [Usaco2010 Hol]Dotp 驱逐猪猡 ——期望DP

    思路和BZOJ 博物馆很像. 同样是高斯消元 #include <map> #include <ctime> #include <cmath> #include & ...

  4. 源码分析 脱壳神器ZjDroid工作原理

    0. 神器ZjDroid Xposed框架的另外一个功能就是实现应用的简单脱壳,其实说是Xposed的作用其实也不是,主要是模块编写的好就可以了,主要是利用Xposed的牛逼Hook技术实现的,下面就 ...

  5. Linux 下测试磁盘读写 I/O 速度的方法汇总

    在分布式异构存储系统中,我们经常会需要测量获取不同节点中硬盘/磁盘的读写 I/O 速度,下面是 Linux 系统下一些常用测试方法(之后不定期更新): 1.使用 hdparm 命令这是一个是用来获取A ...

  6. 使用sudo,mvn command not found

    一个简单的解决办法是,编辑你当前用户的 .bashrc 文件,添加下面这行内容: alias sudo="sudo env PATH=$PATH" 因为系统预装的 sudo 在编译 ...

  7. calc BZOJ 2655

    calc [问题描述] 一个序列a1,...,an是合法的,当且仅当: 长度为给定的n. a1,...,an都是[1,A]中的整数. a1,...,an互不相等. 一个序列的值定义为它里面所有数的乘积 ...

  8. PXC小结

    PXC使用到的端口号 3306 数据库对外服务的端口号(视具体情况而定) 4444 请求SST SST: 指数据一个镜象传输 xtrabackup , rsync ,mysqldump  4567 : ...

  9. 转 Linux文件管理

    Linux文件管理 http://www.cnblogs.com/vamei/archive/2012/09/09/2676792.html 作者:Vamei 出处:http://www.cnblog ...

  10. PHPstorm注册码(7.1.3)

    UserName EMBRACE ===== LICENSE BEGIN ===== 18710-12042010 00000EsehCiFamTQe"7jHcPB16QOyk S" ...