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& ...
随机推荐
- UITableView滑动动画+FPSLabel
主要使用了tableView的代理方法 行将要显示的时候 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableView ...
- noip2018——题解&总结
近期正在疯狂复习某些东西,这篇博客尽量年底更完……(Day2T2除外) 好了,所有的希望都破灭了,原来这就是出题人的素质.——一个被欺骗的可怜 $OIer$ 人生中倒数第三次 $noip$ (Mayb ...
- Spoj-FACVSPOW Factorial vs Power
Consider two integer sequences f(n) = n! and g(n) = an, where n is a positive integer. For any integ ...
- LightOJ1106 Gone Fishing
Gone Fishing John is going on a fishing trip. He has h hours available, and there are n lakes in the ...
- HDU 4803 Poor Warehouse Keeper (贪心+避开精度)
555555,能避开精度还是避开精度吧,,,,我们是弱菜.. Poor Warehouse Keeper Time Limit: 2000/1000 MS (Java/Others) Memor ...
- android layout
android的视图分为两类,一类是布局,另一个类是控件 一.LinearLayout(线性布局) 最常用布局之一,线性布局的特性是每添加一个控件默认会在上个控件的下面占一行. <LinearL ...
- Codeforces 864E Fire(DP)
题目链接 Fire 题意 有n个物品,每个物品的挽救时间代价为ti, 消失时刻为di, 价值为pi. 如果要救某个物品,必须在他消失之前救出来. 同一时刻最多只能救一件物品. 当前耗时为当前已经救出的 ...
- T2038 香甜的黄油 codevs
http://codevs.cn/problem/2038/ 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题目描述 Description 农夫John ...
- P2007 魔方
洛谷——P2007 魔方 题目背景 常神牛从来没接触过魔方,所以他要借助计算机来玩.即使是这样,他还是很菜. 题目描述 常神牛家的魔方都是3*3*3的三阶魔方,大家都见过. (更正:3 4以图为准.) ...
- python 获取时间 存入文件
1读文件: file_path_name = '/home/robot/bzrobot_ws/src/bzrobot/bzrobot_comm/led_show_data/'+file_name+'. ...