/**
* 身份证图片下载到服务器本地 并返回图片Base64编码字节数据
*/
public String downLoad(String downLoadUrl) {
String randomNo = getRandomNo();
//项目文件夹下生成download文件夹
File savePath = new File(System.getProperty("user.dir") + File.separator + "download");
if (!savePath.exists()) {
savePath.mkdir();
}
URL url = null;
try {
url = new URL(downLoadUrl);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath.getPath() + File.separator + randomNo + ".jpeg"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
File file = new File(savePath.getPath() + File.separator + randomNo + ".jpeg");
Thumbnails.of(file)
.scale(0.5f) //图片大小(长宽)压缩 从0按照
.outputQuality(0.5f) //图片质量压缩比例 从0-1,越接近1质量越好
.toOutputStream(new FileOutputStream(savePath.getPath() + File.separator + randomNo+"1" + ".jpeg"));
File file2 = new File(savePath.getPath() + File.separator + randomNo+"1" + ".jpeg");
//读取图片字节数组
InputStream ins = null;
byte[] data = null;
ins = new FileInputStream(file2);
data = new byte[ins.available()];
ins.read(data);
ins.close();
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
System.out.println(encoder.encode(data));
return encoder.encode(data);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
savePath.delete();
}
return null;
}
/**
* 获取随机流水号
*/
public String getRandomNo() {
String timeStr = DateUtil.getCurrentTime();
//随机数 不小于6位数
Random random = new Random();
int rd = random.nextInt(899999);
rd = rd + 100000;
String rdStr = Integer.toString(rd);
String randomStr = timeStr.concat(rdStr);
return randomStr;
}
图片转Base64编码字节数据
最新推荐文章于 2023-04-13 09:40:48 发布