2011-12-13 48 views
9

我试图将一个布局保存到SDCard中的图像,但我得到这个错误。我尝试了几个代码,我在这个论坛中发现,但他们都有相同的压缩调用给出错误。不能压缩一个回收的位图

这是我用来保存图像的代码:

private Bitmap TakeImage(View v) { 
     Bitmap screen = null; 
     try { 
      v.setDrawingCacheEnabled(true); 

      v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 
      v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 

      v.buildDrawingCache(true); 
      screen = v.getDrawingCache(); 
      v.setDrawingCacheEnabled(false); // clear drawing cache 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return screen; 
    } 

这是代码为它保存在SD卡:

private void saveGraph(Bitmap graph, Context context) throws IOException { 
     OutputStream fOut = null; 
     File file = new File(Environment.getExternalStorageDirectory() 
       + File.separator + "test.jpg"); 
     fOut = new FileOutputStream(file); 

     graph.compress(Bitmap.CompressFormat.JPEG, 85, fOut); 
     fOut.flush(); 
     fOut.close(); 

     MediaStore.Images.Media.insertImage(getContentResolver(), 
       file.getAbsolutePath(), file.getName(), file.getName()); 
} 

,我发现了错误:

Can't compress a recycled bitmap in the compress call!

回答

13

这可能会导致位图被回收:

v.setDrawingCacheEnabled(false); // clear drawing cache 

如果你想位图挂起的时间更长,那么你应该复制它。

+0

就是这样!我拿出那条线,完美地工作!谢谢!!! – Lucia

+2

你不应该拿出线;从缓存提供的位图可以随时由其拥有的视图回收。您真的需要使用'Bitmap.copy()'来代替您自己的Bitmap副本。 –

+0

你能解释如何复制它吗? – Lucia

14

这解决了我的问题。

View drawingView = get_your_view_for_render; 
drawingView.buildDrawingCache(true); 
Bitmap bitmap = drawingView.getDrawingCache(true).copy(Config.RGB_565, false); 
drawingView.destroyDrawingCache(); 
// bitmap is now OK for you to use without recycling errors.