bitmap.copy()抛出内存不足错误

时间:2014-05-20 15:01:06

标签: android universal-image-loader

我正在使用universal-image-loader库来加载图片,但是在某些情况下,当我在加载的位图文件上调用copy()时,我得到OutOfMemoryError。 这是我的代码:

    ImageLoader.getInstance().loadImage(path, new ImageLoadingListener() {

        @Override
        public void onLoadingStarted(String arg0, View arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
            bm = arg2;
        }

        @Override
        public void onLoadingCancelled(String arg0, View arg1) {
            // TODO Auto-generated method stub

        }
    });
 Bitmap bm2= bm.copy(Bitmap.Config.ARGB_8888, true); //where the crash happens

我需要第二个Bitmap不可变,所以我可以借鉴它。

6 个答案:

答案 0 :(得分:14)

首先尝试找一点时间阅读有关位图的正式官方文档:Displaying Bitmaps Efficiently

它会让您了解java.lang.OutofMemoryError发生的原因和时间。以及如何避免它。

您的问题如何:请参阅此文章:Android: convert Immutable Bitmap into Mutable

  

但是从API级别11开始只有options.inMutable可用于加载   将文件存入可变位图。

     

因此,如果我们正在构建API级别低于11的应用程序,那么   我们必须找到一些其他选择。

     

另一种方法是通过复制源

来创建另一个位图      

<强> bitmap. mBitmap = mBitmap.copy(ARGB_8888 ,true);

     

但如果源文件很大,则会抛出OutOfMemoryException 。   实际上,如果我们想要编辑原始文件,那么我们将面对   这个问题。我们应该能够将至少图像加载到内存中,但是   大多数情况下,我们无法将另一个副本分配到内存中。

     

因此,我们必须将解码后的字节保存到某些地方并清除   现有的位图,然后创建一个新的可变位图并加载回来   将字节再次保存到位图中。即使复制字节,我们也无法创建   记忆中的另一个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();

here是示例代码。

答案 1 :(得分:3)

除了确保复制或显示的位图不是很大之外,您无法对位图内存错误做很多事情。幸运的是,通用图像加载器具有通过更改配置来压缩位图的功能。所以试试Bitmap.Config.RGG_565吧。它应该占位图内存占用量的一半。您还可以请求大堆大小。您可以做的另一件事是复制位图的缩放版本。

答案 2 :(得分:2)

正如Illegel Argument所说,你需要确保Bitmap不太大。此外,请确保您一次只将一个位图加载到内存中。

您可以使用BitmapFactory

动态缩放位图
Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
image.setImageBitmap(Bitmap.createScaledBitmap(b, 300, 300, false));

答案 3 :(得分:2)

要感谢它发生在您的设备上,而不仅仅发生在用户的设备上。

1)你需要应对的事情,并做出适当的反应。显示错误消息,或加载位图的较低分辨率。您的应用程序将在多种设备上运行,每种设备都有不同的内存量。

2)在每次操作后使用重要函数Bitmap.recycle,这会使您的旧位图变为冗余。这将立即释放内存用于下一步工作,而无需等待GC运行,并可能出现内存不足错误。

答案 4 :(得分:1)

从网站下载此代码

http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

提取其ImageLoader,文件缓存,内存缓存类在你的位图中使用它们来做一些根本不会产生内存不足的事情并且会缓存图像并提高性能

答案 5 :(得分:1)

使用此代码填写您的目的

在你的代码中创建以下类,并在上次使用imageloader加载url传递url,imageview和drawable以显示incase url不返回任何图像

FileCache.java

public class FileCache {

private File cacheDir;

public FileCache(Context context){
    //Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
    else
        cacheDir=context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();
}

public File getFile(String url){
    //I identify images by hashcode. Not a perfect solution, good for the demo.
    String filename=String.valueOf(url.hashCode());
    //Another possible solution (thanks to grantland)
    //String filename = URLEncoder.encode(url);
    File f = new File(cacheDir, filename);
    return f;

}

public void clear(){
    File[] files=cacheDir.listFiles();
    if(files==null)
        return;
    for(File f:files)
        f.delete();
}

}

MemoryCache.java

public class MemoryCache {
private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());

public Bitmap get(String id){
    if(!cache.containsKey(id))
        return null;
    SoftReference<Bitmap> ref=cache.get(id);
    return ref.get();
}

public void put(String id, Bitmap bitmap){
    cache.put(id, new SoftReference<Bitmap>(bitmap));
}

public void clear() {
    cache.clear();
}
}

Utils.java

public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
    final int buffer_size=1024;
    try
    {
        byte[] bytes=new byte[buffer_size];
        for(;;)
        {
          int count=is.read(bytes, 0, buffer_size);
          if(count==-1)
              break;
          os.write(bytes, 0, count);
        }
    }
    catch(Exception ex){}
}
}

ImageLoader.java

public class ImageLoader {

MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService; 

public ImageLoader(Context context){
    fileCache=new FileCache(context);
    executorService=Executors.newFixedThreadPool(5);
}

final int stub_id = R.drawable.no_image;
public void DisplayImage(String url, ImageView imageView)
{
    imageViews.put(imageView, url);
    Bitmap bitmap=memoryCache.get(url);
    if(bitmap!=null)
        imageView.setImageBitmap(bitmap);
    else
    {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageView imageView)
{
    PhotoToLoad p=new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url) 
{
    File f=fileCache.getFile(url);

    //from SD cache
    Bitmap b = decodeFile(f);
    if(b!=null)
        return b;

    //from web
    try {
        Bitmap bitmap=null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex){
       ex.printStackTrace();
       return null;
    }
}

//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
    try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE=70;
        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }

        //decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

//Task for the queue
private class PhotoToLoad
{
    public String url;
    public ImageView imageView;
    public PhotoToLoad(String u, ImageView i){
        url=u; 
        imageView=i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;
    PhotosLoader(PhotoToLoad photoToLoad){
        this.photoToLoad=photoToLoad;
    }

    @Override
    public void run() {
        if(imageViewReused(photoToLoad))
            return;
        Bitmap bmp=getBitmap(photoToLoad.url);
        memoryCache.put(photoToLoad.url, bmp);
        if(imageViewReused(photoToLoad))
            return;
        BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
        Activity a=(Activity)photoToLoad.imageView.getContext();
        a.runOnUiThread(bd);
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad){
    String tag=imageViews.get(photoToLoad.imageView);
    if(tag==null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
    Bitmap bitmap;
    PhotoToLoad photoToLoad;
    public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
    public void run()
    {
        if(imageViewReused(photoToLoad))
            return;
        if(bitmap!=null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

}

将此代码称为要缓存或下载或管理图像的代码

  imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
相关问题