web-dev-qa-db-ja.com

InputStream(Image)をByteArrayInputStreamに変換します

私がこれをどのように行うことになっているのかわかりません。どんな助けでもいただければ幸いです

16
user398371

入力ストリームから読み取って ByteArrayOutputStream に書き込み、そのtoByteArray()を呼び出してバイト配列を取得します。

それから読み取るバイト配列の周りに ByteArrayInputStream を作成します。

ここに簡単なテストがあります:

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

または、最初にバイト配列に変換し、次にバイト配列入力ストリームに変換します。

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
anvarik

Org.Apache.commons.io .IOUtils#toByteArray(Java.io.InputStream)を使用できます

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