内存泄漏之Bitmap.copy()抛出内存溢出问题解决方法

最近在低版本的设备上处理图片,在Bitmap.copy(Bitmap.Config.ARGB_8888, true)这个方法抛出内存溢出问题。

解决方法
First of all try to find a little time to read good official documentation about bitmaps: Displaying Bitmaps Efficiently

It will give you understanding why and when java.lang.OutofMemoryError happens. And how to avoid it.

What about your question: see this article: Android: convert Immutable Bitmap into Mutable
从API级别11只 options.inMutable 可加载文件转换成可变位,一种选择是通过复制源创建另一个位图。 mBitmap = mBitmap.copy(ARGB_8888,true);
但会抛出 OutOfMemoryException异常 如果源文件是很大的。其实柜面如果我们要编辑的原始文件,那么我们将面临这个问题。我们应该能够在-至少图像加载到内存中,但最让我们无法分配另一个拷贝到内存中。
所以,我们必须节省去codeD字节到一些地方和明确现有的位图,然后创建一个新的可变位并加载回 保存成字节再度位。即使复制我们不能创建字节另一个的ByteBuffer 内存中。在这种情况下,需要使MappedByteBuffer ,将分配一个磁盘文件中的字节。

替代代码

//this is the file going to use temporally to save the bytes. 

File file = new File("/mnt/sdcard/sample/temp.txt");
file.getParentFile().mkdirs();

//Open an RandomAccessFile
/*Make sure you have added uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
into AndroidManifest.xml file*/
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); 

// get the width and height of the source bitmap.
int width = bitmap.getWidth();
int height = bitmap.getHeight();

//Copy the byte to the file
//Assume source bitmap loaded using options.inPreferredConfig = Config.ARGB_8888;
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, width*height*4);
bitmap.copyPixelsToBuffer(map);
//recycle the source bitmap, this will be no longer used.
bitmap.recycle();
//Create a new bitmap to load the bitmap again.
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
map.position(0);
//load it back from temporary 
bitmap.copyPixelsFromBuffer(map);
//close the temporary file and channel , then delete that also
channel.close();
randomAccessFile.close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值