Java Graphics How to - Convert InputStream from Image to ByteArrayInputStream








Question

We would like to know how to convert InputStream from Image to ByteArrayInputStream.

Answer

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
// w w  w  .j  a va 2 s  . c o m
public class Main {

  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);
    }
    in.close();
    
    byte[] data = bao.toByteArray();
 
    ByteArrayInputStream bin = new ByteArrayInputStream(data);
    System.out.println(bin.available());
  }
}