2010-08-16 7 views
12

Je ne suis pas sûr de la façon dont je suis censé faire cela. Toute aide serait la bienvenueConvertir InputStream (Image) en ByteArrayInputStream

+0

Depuis ByteArrayInputStream sont construire à partir byte [] http://stackoverflow.com/questions/2163644/in-java-how-can-i-convert-an-inputstream-into-a-byte-array- byte http://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-in-java – h3xStream

+0

Que faites-vous exactement avec des images où vous n'utilisez pas les classes 'javax.imageio'? – Powerlord

+0

Téléchargement vers Amazon S3 ... La bibliothèque Java que j'utilise ByteArrayInputStream requis pour toutes les données non-basées sur la chaîne – user398371

Répondre

18

Lire à partir du flux d'entrée et écrire dans un ByteArrayOutputStream, puis appeler son toByteArray() pour obtenir le tableau d'octets.

Créez un ByteArrayInputStream autour du tableau d'octets à lire.

Voici un test rapide:

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

J'étais presque là! Merci pour l'exemple tho. Un vrai maître d'IO! – user398371

+0

Vous êtes les bienvenus :) – naikus

1

Ou d'abord le convertir en un tableau d'octets, puis à un 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); 
Questions connexes