最近在做图片预览显示时,需要将InputStream转成byte[],再转成base64,返回给前端展示
下面复习一下
/**
* InputStream转成byte[]
* @param inStream
* @return
* @throws IOException
*/
public static final byte[] inputTobyte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] byte= swapStream.toByteArray();
return byte;
}
byte转base64
String base64encode = new BASE64Encoder().encode(bytes);
//去掉空格,直接转的话会有换行问题,在前端展示会导致出不来 base64encode = base64encode.replaceAll("[\\s*\t\n\r]", "");
以上亲测有效,踩过的坑