Convert InputStream(Image) to ByteArrayInputStream

坚强是说给别人听的谎言 提交于 2019-12-17 22:41:15

问题


Not sure about how I am supposed to do this. Any help would be appreciated


回答1:


Read from input stream and write to a ByteArrayOutputStream, then call its toByteArray() to obtain the byte array.

Create a ByteArrayInputStream around the byte array to read from it.

Here's a quick test:

import java.io.*;

public class Test {


       public static void main(String[] arg) throws Throwable {
          File f = new File(arg[0]);
          InputStream in = new FileInputStream(f);

          byte[] buff = new byte[8000];

          int bytesRead = 0;

          ByteArrayOutputStream bao = new ByteArrayOutputStream();

          while((bytesRead = in.read(buff)) != -1) {
             bao.write(buff, 0, bytesRead);
          }

          byte[] data = bao.toByteArray();

          ByteArrayInputStream bin = new ByteArrayInputStream(data);
          System.out.println(bin.available());
       }
}



回答2:


Or first convert it to a byte array, then to a bytearrayinputstream.

File f = new File(arg[0]);
InputStream in = new FileInputStream(f);
// convert the inpustream to a byte array
byte[] buf = null;
try {
    buf = new byte[in.available()];
    while (in.read(buf) != -1) {
    }
} catch (Exception e) {
    System.out.println("Got exception while is -> bytearr conversion: " + e);
}
// now convert it to a bytearrayinputstream
ByteArrayInputStream bin = new ByteArrayInputStream(buf);



回答3:


You can use org.apache.commons.io.IOUtils#toByteArray(java.io.InputStream)

InputStream is = getMyInputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(IOUtils.toByteArray(is));


来源:https://stackoverflow.com/questions/3495942/convert-inputstreamimage-to-bytearrayinputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!