Java 将 InputStream(Image) 转换为 ByteArrayInputStream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3495942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:17:54  来源:igfitidea点击:

Convert InputStream(Image) to ByteArrayInputStream

javaimageinputstream

提问by user398371

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

不确定我应该如何做到这一点。任何帮助,将不胜感激

采纳答案by naikus

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

从输入流中读取并写入ByteArrayOutputStream,然后调用它toByteArray()以获取字节数组。

Create a ByteArrayInputStreamaround the byte array to read from it.

在字节数组周围创建一个ByteArrayInputStream以从中读取。

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());
       }
}

回答by anvarik

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);

回答by Jaroslav

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

您可以使用 org.apache.commons.io。IOUtils#toByteArray(java.io.InputStream)

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