ByteToInputStream.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package com.yihu.jw.utils;
  2. import org.apache.commons.codec.binary.Base64;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.io.ByteArrayInputStream;
  6. import java.io.ByteArrayOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. /**
  10. * Created by Trick on 2019/8/26.
  11. */
  12. public class ByteToInputStream {
  13. private static final Logger logger = LoggerFactory.getLogger(ByteToInputStream.class);
  14. public InputStream byte2Input(byte[] buf) {
  15. return new ByteArrayInputStream(buf);
  16. }
  17. public byte[] input2byte(InputStream inStream)
  18. throws IOException {
  19. ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
  20. byte[] in2b = null;
  21. try {
  22. byte[] buff = new byte[100];
  23. int rc = 0;
  24. while ((rc = inStream.read(buff, 0, 100)) > 0) {
  25. swapStream.write(buff, 0, rc);
  26. }
  27. in2b = swapStream.toByteArray();
  28. }catch (Exception e){
  29. logger.error(e.toString());
  30. }finally {
  31. inStream.close();
  32. swapStream.close();
  33. }
  34. return in2b;
  35. }
  36. public String getBase64FromInputStream(InputStream in) {
  37. // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
  38. byte[] data = null;
  39. // 读取图片字节数组
  40. ByteArrayOutputStream swapStream = null;
  41. try {
  42. swapStream = new ByteArrayOutputStream();
  43. byte[] buff = new byte[100];
  44. int rc = 0;
  45. while ((rc = in.read(buff, 0, 100)) > 0) {
  46. swapStream.write(buff, 0, rc);
  47. }
  48. data = swapStream.toByteArray();
  49. } catch (IOException e) {
  50. logger.error("ByteToInputStream.getBase64FromInputStream:"+e.toString());
  51. } finally {
  52. if (in != null) {
  53. try {
  54. swapStream.close();
  55. in.close();
  56. } catch (IOException e) {
  57. logger.error(e.toString());
  58. }
  59. }
  60. }
  61. return new String(Base64.encodeBase64(data));
  62. }
  63. }