【问题标题】:How do I download Bitmaps and save to the SD card without running out of memory?如何下载位图并保存到 SD 卡而不会耗尽内存?
【发布时间】:2011-08-03 11:26:10
【问题描述】:

我正在寻找下载位图数组、稍作修改然后保存到 SD 卡的最佳方法。

我听说ByteArrayOutputStream 不适合使用,因为它将图像加载到设备的 RAM 中。相反,我可能应该使用BufferedInputStream 和FileOutputStream 之类的东西,但是我不知道如何在使用此方法保存位图之前更改它们。

谢谢

【问题讨论】:

    标签: android download bitmap android-3.0-honeycomb bufferedinputstream


    【解决方案1】:

    你不会喜欢这个答案:你不能(至少,对于 Android 框架来说不是)。

    唯一的选择是downscale the image,以便它适合内存;并定期致电recycle()和System.gc()尽快释放内存。

    【讨论】:

    • 是的,这正是我所担心的。我想我能做的是使用 BufferedInputStream 下载图像,然后再进行位图操作。不是世界上最好的东西,但幸运的是我使用 AsyncTask 下载图像,所以我可以在 onPostExecute() 方法中完成位图的工作。非常感谢:)
    • 还有另一个建议:使用IntentService 而不是AsyncTask 来实现您的长时间运行的任务(下载、图像处理)(请参阅stackoverflow.com/questions/2620917/… google.com/events/io/2010/sessions/…)
    【解决方案2】:

    您可以使用 InputStream 创建位图:

    Bitmap bm = BitmapFactory.decodeStream(inputStream);
    

    然后在您处理完 Bitmap 并存储它们之后,您必须使用:

    bm.recycle();
    bm = null;
    

    避免OutOfMemoryExceptions。

    编辑:

    将其写入文件:

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

    【讨论】:

    • 是的,谢谢,我知道,但是如何在不使用 ByteArrayOutputStream 的情况下将位图写入 SD 卡上的文件?
    • 谢谢你 - 但你的代码是直接从 inputStream 而不是 Bitmap 读取的:(
    猜你喜欢
    • 2012-10-21
    • 2010-11-06
    • 2012-08-04
    • 2011-02-07
    • 2011-04-05
    • 2018-10-17
    • 2013-12-02
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多