最近在低版本的设备上处理图片,在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();