简体   繁体   中英

Using libraries to read inputstream into arrays in android

I am trying to save data (specifically an image) received from an input stream (from a socket) into a byte array. I have checked two options:

a. Using java.io.ByteArrayOutputStream , and then use the following code:

  InputStream in = socket.getInputStream();
  byte[] imageInBytes = in.toByteArray();

the problem there is that eclipse does not recognize the method toByteArray() . How can I copy/change the InputStream (in this case in ) into a ByteArrayOutputStream in order to use that method?

b. Using org.apache.commons.io.IOUtils , and then use the following:

    InputStream in = socket.getInputStream();
    byte[] imageInBytes = IOUtils.toByteArray(in);

which I added commons-io-2.4.jar in the java build path and copy it in the /libs directory, but still it does not do what it suppose, and an error is given due to byte[] imageInBytes = IOUtils.toByteArray(in); .

I am using gingerbread, by the way.

For both cases I was wondering whether I am doing it right, and how to fix the mentioned problem.

Try this:

InputStream inputStream = socket.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);

OR:

InputStream inputStream = socket.getInputStream();
Drawable drawable = Drawable.createFromStream(inputStream, null);
imageView.setImageDrawable(drawable);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM