Java客户端:调用EyeKey HTTP接口进行人脸对比
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接口进行人脸对比的更多相关文章
- Java与WCF交互(一):Java客户端调用WCF服务
最近开始了解WCF,写了个最简单的Helloworld,想通过java客户端实现通信.没想到以我的基础,居然花了整整两天(当然是工作以外的时间,呵呵),整个过程大费周折,特写下此文,以供有需要的朋友参 ...
- java如何调用对方http接口(II)
java如何调用接口 在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适,所以,问题来了,java如何调用接口?很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对 ...
- Java与WCF交互(一):Java客户端调用WCF服务 【转】
原文:http://www.cnblogs.com/downmoon/archive/2010/08/24/1807161.html 最近开始了解WCF,写了个最简单的Helloworld,想通过ja ...
- 转载——Java与WCF交互(一):Java客户端调用WCF服务
最近开始了解WCF,写了个最简单的Helloworld,想通过java客户端实现通信.没想到以我的基础,居然花了整整两天(当然是工作以外的时间,呵呵),整个过程大费周折,特写下此文,以供有需要的朋友参 ...
- 使用java客户端调用redis
Redis支持很多编程语言的客户端,有C.C#.C++.Clojure.Common Lisp.Erlang.Go.Lua.Objective-C.PHP.Ruby.Scala,甚至更时髦的Node. ...
- java客户端调用ftp上传下载文件
1:java客户端上传,下载文件. package com.li.utils; import java.io.File; import java.io.FileInputStream; import ...
- Java 常调用的Webservice接口的方法
WebService是基于Web的服务,WebService使用SOAP协议实现跨编程语言和跨操作系统平台,接收和响应外部系统的某种请求,从而实现远程调用.WebService采用HTTP协议传输数据 ...
- Java客户端调用.NET的WebService
项目需要去调用.NET的WebSrevice,本身是Java,研究了半天,终于有些头绪,记下来. 1,新建.NET WebService.只在原方法上加上一个string类型的参数str [WebMe ...
- java客户端调用c#的webservice服务
此处使用到了CXF框架,可以使用以下坐标从maven仓库中获取相关jar包: <dependency> <groupId>org.apache.cxf</groupId& ...
随机推荐
- Redis的数据类型及相关操作命令
redis 基础内容 —— redis的数据类型及相关操作的Linux命令.所谓大厦千层基础承载,希望大家认真学习这一讲: 一.redis 的五大数据类型: 1.String(字符串): 2.List ...
- docker 给容器配置ip(和主机一个网段)
docker 给容器配置ip(和主机一个网段).详情参考:http://www.xiaomastack.com/2015/02/06/docker-static-ip/ #/bin/bash ] || ...
- 接口自动化测试框架--http请求的get、post方法的实现
已知两种方法.一种是通过httpclient实现(貌似很简单,以后看一下),一种是以下方法: Client实现: package common; import com.alibaba.fastjson ...
- C Looooops(poj 2115)
大致题意: 对于C的for(i=A ; i!=B ;i +=C)循环语句,问在k位存储系统中循环几次才会结束. 若在有限次内结束,则输出循环次数. 否则输出死循环. 解题思路: 题意不难理解,只是利用 ...
- 洛谷 [T21776] 子序列
题目描述 你有一个长度为 \(n\) 的数列 \(\{a_n\}\) ,这个数列由 \(0,1\) 组成,进行 \(m\) 个的操作: \(1\ l\ r\) :把数列区间$ [l,r]$ 内的所有数 ...
- Laravel 5 Form 和 HTML 的使用
最近在用 laravel 5 做例子,在做到表单的时候,习惯性的使用 Form::open() 结果发现提示错误,没有这个类, 好吧,找了找,发现 在laravel 5 中,把 from 和 html ...
- R语言入门视频笔记--9--随机与数据描述分析
古典概型的样本总量是一定的,且每种可能的可能性是相同的, 1.中位数:median(x) 2.百分位数:quantile(x)或者quantile(x,probe=seq(0,1,0.2)) #后面这 ...
- idea抛异常方式
选中需要抛异常的行,按alt+enter或者ctrl+alt+t,然后上下键选择自己抛异常的方式即可,如下图:
- php 笔记 汇总 学习
php命令行:通过命令行进入到当前要被执行的php文件路径,然后输入php环境可执行路径(后面包含php.exe),然后输入要被执行的php文件,比如runData.php即可. php框架:yaf. ...
- crontab 实际的应用
每二天执行一次: 0 0 */2 * * command #注意分,时不能为星*,否则每分钟执行 每天零晨01,03执行: 0 01,03 * * * command 每2小时执行一次 0 */2 * ...