本demo两个类
package com.ailiyun.face;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
//@SuppressWarnings("restriction")
public class FaceDemoVerify {
private static final String ak_id = "LTAI4FsFovihVGbkSBt3XZMA";
private static final String ak_secret = "qkHdFOcpxDshdgOAarDwmpESFDbo2H";
private static final String url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/verify";
/*
* 计算MD5+BASE64
*/
public static String MD5Base64(String s) {
if (s == null)
return null;
String encodeStr = "";
byte[] utfBytes = s.getBytes();
MessageDigest mdTemp;
try {
mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(utfBytes);
byte[] md5Bytes = mdTemp.digest();
BASE64Encoder b64Encoder = new BASE64Encoder();
encodeStr = b64Encoder.encode(md5Bytes);
} catch (Exception e) {
throw new Error("Failed to generate MD5 : " + e.getMessage());
}
return encodeStr;
}
/*
* 计算 HMAC-SHA1
*/
public static String HMACSha1(String data, String key) {
String result;
try {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
result = (new BASE64Encoder()).encode(rawHmac);
} catch (Exception e) {
throw new Error("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
/*
* 等同于javaScript中的 new Date().toUTCString();
*/
public static String toGMTString(Date date) {
SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
return df.format(date);
}
/*
* 发送POST请求
*/
//如果发送的是转换为base64编码后后面加请求参数type为1,如果请求的是图片的url则不用加type参数。
public static String sendPost(String body) throws Exception {
// String body = "{\"content_1\": \"" + content_1 + "\", \"content_2\":\"" + content_2 + "\", \"type\":\"" + "1" + "\"}";
PrintWriter out = null;
BufferedReader in = null;
String result = "";
int statusCode = 200;
try {
URL realUrl = new URL(url);
/*
* http header 参数
*/
String method = "POST";
// 返回值类型
String accept = "application/json";
// 请求内容类型
String content_type = "application/json";
String path = realUrl.getFile();
// GMT时间
String date = toGMTString(new Date());
// 1.对body做MD5+BASE64加密
String bodyMd5 = MD5Base64(body);
String stringToSign = method + "\n" + accept + "\n" + bodyMd5+ "\n" + content_type + "\n" + date + "\n"
+ path;
// 2.计算 HMAC-SHA1
String signature = HMACSha1(stringToSign, ak_secret);
// 3.得到 authorization header
String authHeader = "Dataplus " + ak_id + ":" + signature;
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("Accept", accept);
conn.setRequestProperty("Content-type", content_type);
conn.setRequestProperty("Date", date);
// 认证信息
conn.setRequestProperty("Authorization", authHeader);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(body);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
statusCode = ((HttpURLConnection) conn).getResponseCode();
if (statusCode != 200) {
in = new BufferedReader(new InputStreamReader(((HttpURLConnection) conn).getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (statusCode != 200) {
throw new IOException("\nHttp StatusCode: " + statusCode + "\nErrorMessage: " + result);
}
return result;
}
public static String encodeImageToBase64(File file) throws Exception {
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
// loggerger.info("图片的路径为:" + file.getAbsolutePath());
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
in = new FileInputStream(file);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
throw new Exception("图片上传失败,请联系客服!");
}
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(data);
return base64;//返回Base64编码过的字节数组字符串
}
public static void main(String[] args) throws Exception {
String url ="C:\\Users\\dell\\Desktop\\证件\\2.jpg";
String url1 ="C:\\Users\\dell\\Desktop\\证件\\3.jpg";
//图片压缩
ImgCompress.demo(url);
ImgCompress.demo(url1);
File picBase641 = new File(url1);
File picBase64 = new File(url);
String pic = encodeImageToBase64(picBase64);
String pic1 = encodeImageToBase64(picBase641);
//提出base64编码的换行符问题
String data = pic.replaceAll("[\\s*\t\n\r]", "");
String data2 = pic1.replaceAll("[\\s*\t\n\r]", "");
data = "'" + data + "'";
data2 = "'" + data2 + "'";
String body = "{\"type\":1,\n" +
"\"content_1\":"+data+",\n" +
"\"content_2\":"+data2+"\n" +
"}";
String response = sendPost(body);
System.out.println(response.toString());
}
}
阿里云接口限制了传输数据的大小,所以高清图片需要压缩成缩率图进行上传
压缩图片代码
package com.ailiyun.face;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.*;
/**
* 图片压缩处理
* @author Felix
*/
public class ImgCompress {
private Image img;
private int width;
private int height;
private static String url;
// @SuppressWarnings("deprecation")
// public static void main(String[] args) throws Exception {
// System.out.println("开始:" + new Date().toLocaleString());
// ImgCompress imgCom = new ImgCompress("C:\\Users\\dell\\Desktop\\证件\\my.jpg");
// imgCom.resizeFix(400, 400);
// System.out.println("结束:" + new Date().toLocaleString());
// }
public static void demo(String u) throws IOException {
url=u;
ImgCompress imgCom = new ImgCompress(u);
imgCom.resizeFix(400, 400);
}
/**
* 构造函数
*/
public ImgCompress(String fileName) throws IOException {
File file = new File(fileName);// 读入文件
img = ImageIO.read(file); // 构造Image对象
width = img.getWidth(null); // 得到源图宽
height = img.getHeight(null); // 得到源图长
}
/**
* 按照宽度还是高度进行压缩
* @param w int 最大宽度
* @param h int 最大高度
*/
public void resizeFix(int w, int h) throws IOException {
if (width / height > w / h) {
resizeByWidth(w);
} else {
resizeByHeight(h);
}
}
/**
* 以宽度为基准,等比例放缩图片
* @param w int 新宽度
*/
public void resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
resize(w, h);
}
/**
* 以高度为基准,等比例缩放图片
* @param h int 新高度
*/
public void resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
resize(w, h);
}
/**
* 强制压缩/放大图片到固定的大小
* @param w int 新宽度
* @param h int 新高度
*/
public void resize(int w, int h) throws IOException {
// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
File destFile = new File(url);
FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
// 可以正常实现bmp、png、gif转jpg
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image); // JPEG编码
out.close();
}
}