图片转base64

由于使用url请求第三方,在传输路径的时候sdk处理方式:

 if (param.containsKey("path")) {
this.getFileData(param, "path", "fname", "data");
this.getFileData(param, "path2", "fname2", "data2");
this.getFileData(param, "path3", "fname3", "data3");
}
将传输过来的图片进行处理,此方法处理本地上传路径,即如果部署到服务器,那图片也要上传到服务器。

解决方式,就是不传输图片路径,直接将转码后的图片作为参数传入(接口文档另一要求,不使用内部sdk)
public static InputStream byteByUrl(String urlOrPath) throws IOException {
InputStream in = null;
byte[] bytes;
if (urlOrPath.toLowerCase().startsWith("https")) {
bytes = HttpsUtils.doGet(urlOrPath);
} else if (urlOrPath.toLowerCase().startsWith("http")) {
URL url = new URL(urlOrPath);
return url.openStream();
} else {
File file = new File(urlOrPath);
if (!file.isFile() || !file.exists() || !file.canRead()) {
return null;
}
return new FileInputStream(file);
}
return new ByteArrayInputStream(bytes);
}

/**
* URL转base64
* @param urlOrPath
* @return
* @throws IOException
*/
public static String base64ByUrl(String urlOrPath) throws IOException {
InputStream byteByUrl = byteByUrl(urlOrPath);
byte[] bytes = IOUtils.toByteArray(byteByUrl);
String encoded = Base64.getEncoder().encodeToString(bytes);
return encoded;
}
由以上方法就可以,传入转化后的参数。


posted @ 2020-09-22 14:34  say,sya  阅读(177)  评论(0)    收藏  举报