0

I have code that loads a png file from a url into a ByteArrayOutputStream. Now I want to make this into a bitmap so I can draw it. I tried Bitmap bBack=BitmapFactory.decodeStream(output);, but BitMapFactory will not take in a yteArrayOutputStream.

How can I creat a bitmap from a ByteArrayOutputStream object?, code

try {
    URL url = new URL("http://stage.master.embryooptions.healthbanks.com/siteassets/24/ShadyGrove-logo.png");
    InputStream is = (InputStream) url.getContent();
    byte[] buffer = new byte[8192];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = is.read(buffer)) != -1) {
       output.write(buffer, 0, bytesRead);
    }

/////////////////////////////////////////////////////////////////////////////
//   HOW DO I GET A BITMAP?????????
///////////////////////////////////////////////////////////////////////////////
//                  Bitmap bBack=BitmapFactory.decodeStream(output);
    return "";
} catch (MalformedURLException e) {
                    e.printStackTrace();
   return null;
} catch (IOException e) {
   e.printStackTrace();
   return null;
}
Nick Fortescue
  • 43,045
  • 26
  • 106
  • 134
Ted pottel
  • 6,869
  • 21
  • 75
  • 134

2 Answers2

2

Below should work for you:

byte[] bitmapData = output.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData , 0, bitmapData.length);

Note: Be carefull on bitmap loading. Always use BitmapFactory.Options while decoding to bitmap to prevent memory related errors.

Read more.

Devrim
  • 15,345
  • 4
  • 66
  • 74
1

If your goal is to create a Bitmap object from an image downloaded from your URL, then ByteArrayOutputStream isn't necessary. All you need is this:

InputStream is = (InputStream) url.getContent();
Bitmap image = BitmapFactory.decodeStream(is);

You can look at the developer page for BitmapFactory for more info.

Brett Haines
  • 184
  • 3
  • 14