2011-12-13 23 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.