天天看点

android 大位图复制

     android sdk 中的Bitmap类提供了一个实例方法copy用来复制位图,该方法在复制较大图像时

容易造成内存溢出;原因:该方法在复制图像时将在内存中保存两份图像数据。

    为了解决这个问题,可以将大图像写入SD卡中的一个临时文件中,然后再从文件中取出图像。

根据以上思路用代码如下:

public static Bitmap copy(Bitmap srcBmp){

Bitmap destBmp=null;

try{

//创建一个临时文件

File file = new File("/mnt/sdcard/temp/tmp.txt");

file.getParentFile().mkdirs();

RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); 

int width = srcBmp.getWidth();

int height = srcBmp.getHeight();

FileChannel channel = randomAccessFile.getChannel();

MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, width*height*4);

//将位图信息写进buffer

srcBmp.copyPixelsToBuffer(map);

//释放原位图占用的空间

srcBmp.recycle();

//创建一个新的位图

destBmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);

map.position(0);

//从临时缓冲中拷贝位图信息 

destBmp.copyPixelsFromBuffer(map);

channel.close();

randomAccessFile.close();

}

catch(Exception ex){

destBmp=null;

}

return destBmp;

}