栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

BitmapFactory.decodeResource在Android 2.2中返回可变的位图,在Android 1.6中返回不可变的位图

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

BitmapFactory.decodeResource在Android 2.2中返回可变的位图,在Android 1.6中返回不可变的位图

您可以将不可变位图转换为可变位图。

我找到了一种仅使用一个位图的内存的可接受解决方案。

将源位图原始保存(RandomAccessFile)到磁盘上(没有ram内存),然后释放源位图(现在,内存中没有位图),然后,文件信息将加载到另一个位图。通过这种方式,可以制作一次仅在内存中存储一​​个位图的位图副本。

在此处查看完整的解决方案和实现:Android:将不可变位图转换为可变

我对该解决方案进行了改进,现在可以与任何类型的位图(ARGB_8888,RGB_565等)一起使用,并删除临时文件。看我的方法:

/*
* Converts a immutable bitmap to a mutable bitmap. This operation doesn’t allocates
* more memory that there is already allocated.
*
* @param imgIn - Source image. It will be released, and should not be used more
* @return a copy of imgIn, but muttable.



/
public static Bitmap convertToMutable(Bitmap imgIn) {
try {
//this is the file going to use temporally to save the bytes.
// This file will not be a image, it will store the raw image data.
File file = new File(Environment.getExternalStorageDirectory() + File.separator + “temp.tmp”);

    //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 = imgIn.getWidth();    int height = imgIn.getHeight();    Config type = imgIn.getConfig();    //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, imgIn.getRowBytes()*height);    imgIn.copyPixelsToBuffer(map);    //recycle the source bitmap, this will be no longer used.    imgIn.recycle();    System.gc();// try to force the bytes from the imgIn to be released    //Create a new bitmap to load the bitmap again. Probably the memory will be available.     imgIn = Bitmap.createBitmap(width, height, type);    map.position(0);    //load it back from temporary     imgIn.copyPixelsFromBuffer(map);    //close the temporary file and channel , then delete that also    channel.close();    randomAccessFile.close();    // delete the temp file    file.delete();} catch (FileNotFoundException e) {    e.printStackTrace();} catch (IOException e) {    e.printStackTrace();}return imgIn;

}



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/426106.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号