0

I'm looking for the best way to download an array of Bitmaps, modify them a bit and then save to the SD card.

I've heard that ByteArrayOutputStream is a bad idea to use because it loads the image into the RAM of the device. Instead I'm probably supposed to use something like a BufferedInputStream and FileOutputStream, however I don't know how I can alter the Bitmaps before saving them using this method.

Thanks

Michell Bak
  • 13,182
  • 11
  • 64
  • 121

2 Answers2

1

You can create your bitmap from your InputStream using:

Bitmap bm = BitmapFactory.decodeStream(inputStream);

and then after you have processed your Bitmap and stored them you must use:

bm.recycle();
bm = null;

to avoid OutOfMemoryExceptions .

EDIT:

For writing it to a file:

OutputStream fos=new BufferedOutputStream(new FileOutputStream(filePath));
byte buf[]=new byte[1024];
int len;
while((len=is.read(buf))>0)
    fos.write(buf,0,len);
fos.close();
is.close();
jenzz
  • 7,239
  • 6
  • 49
  • 69
Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
1

You will not like the answer: you cannot (at least, not with the Android framework).

The only option is to downscale the image so that it fits in memory; and regularly call recycle()and System.gc() to free memory as soon as possible.

Community
  • 1
  • 1
rds
  • 26,253
  • 19
  • 107
  • 134
  • Yeah, that's pretty much what I feared. I guess what I can do is download the images using a BufferedInputStream and then do my Bitmap manipulating afterwards. Not the best thing in the world, but luckily I was downloading the images using an AsyncTask, so I'll be able to do the Bitmap stuff in the onPostExecute() method. Thanks a lot :) – Michell Bak Aug 03 '11 at 17:25
  • And then another recommendation: implement your long running tasks (downloading, image manipulation) with an `IntentService` rather than an `AsyncTask` (see http://stackoverflow.com/questions/2620917/how-to-handle-an-asynctask-during-screen-rotation http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html) – rds Aug 04 '11 at 08:25