1、base64字符串转inputstream
private static InputStream base2InputStream(String base64string) {
ByteArrayInputStream stream = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bt = decoder.decodeBuffer(base64string);
stream = new ByteArrayInputStream(bt);
} catch (Exception e) {
e.printStackTrace();
}
return stream;
}
2、inputstream 转 base64
方法一、
private static String inputStream2Base64( InputStream is) throws Exception {
byte[] data = null;
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = is.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new Exception("输入流关闭异常");
}
}
}
return Base64.getEncoder().encodeToString(data);
}
方法二、(采用第三方jar的方式)
byte[] byte=IOUtils.toByteArray(inputStream);
String encoded = "data:image/png;base64,"+Base64Util.encode(bytes);