开发者

How do I download Bitmaps and save to the SD card without running out of memory?

开发者 https://www.devze.com 2023-03-25 03:20 出处:网络
I\'m lookin开发者_JS百科g for the best way to download an array of Bitmaps, modify them a bit and then save to the SD card.

I'm lookin开发者_JS百科g 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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号