Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert InputStream(Image) to ByteArrayInputStream

Tags:

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

like image 209
user398371 Avatar asked Aug 16 '10 18:08

user398371


People also ask

How do you convert input streams to bytes?

Example 1: Java Program to Convert InputStream to Byte Arraybyte[] array = stream. readAllBytes(); Here, the readAllBytes() method returns all the data from the stream and stores in the byte array. Note: We have used the Arrays.

How do you write InputStream to ByteArrayOutputStream?

The IOUtils type has a static method to read an InputStream and return a byte[] . InputStream is; byte[] bytes = IOUtils. toByteArray(is); Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray() .

How do you read all bytes from InputStream?

Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.


1 Answers

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());        } } 
like image 198
naikus Avatar answered Nov 15 '22 18:11

naikus