图片转Base64,常遇到图片展示显示不全的问题,下面就进行解决
//图片转Base64,imgList是要转的图片路径,可以是相对路径也可以是绝对路径
private static List getImageBase64Str(List<String> imgList) throws IOException {
List Base64Urllist = new ArrayList();
for (String imgPath : imgList) {
InputStream inputStream = null;
try {
Base64.Encoder encoder = Base64.getEncoder();
String requestMethod = "GET";
String outputStr = null;
inputStream = HttpUtils.httpRequest2(imgPath, requestMethod, outputStr);
byte[] bytes = read(inputStream);
String base64Str = encoder.encodeToString(bytes);
Base64Urllist.add(base64Str);
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
}
}
return Base64Urllist;
}
//处理图片显示不全问题
public static byte[] read(InputStream inputStream) throws IOException {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int num = inputStream.read(buffer);
while (num != -1) {
baos.write(buffer, 0, num);
num = inputStream.read(buffer);
}
baos.flush();
return baos.toByteArray();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}