package com.yihu.jw.utils; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * Created by Trick on 2019/8/26. */ public class ByteToInputStream { private static final Logger logger = LoggerFactory.getLogger(ByteToInputStream.class); public InputStream byte2Input(byte[] buf) { return new ByteArrayInputStream(buf); } public byte[] input2byte(InputStream inStream) throws IOException { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] in2b = null; try { byte[] buff = new byte[100]; int rc = 0; while ((rc = inStream.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } in2b = swapStream.toByteArray(); }catch (Exception e){ logger.error(e.toString()); }finally { inStream.close(); swapStream.close(); } return in2b; } public String getBase64FromInputStream(InputStream in) { // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 byte[] data = null; // 读取图片字节数组 ByteArrayOutputStream swapStream = null; try { swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = in.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } data = swapStream.toByteArray(); } catch (IOException e) { logger.error("ByteToInputStream.getBase64FromInputStream:"+e.toString()); } finally { if (in != null) { try { swapStream.close(); in.close(); } catch (IOException e) { logger.error(e.toString()); } } } return new String(Base64.encodeBase64(data)); } }