2011-12-13 10 views
9

Sto tentando di salvare un layout in un'immagine nella scheda SD ma ottengo questo errore. Ho provato diversi codici che ho trovato in questo forum, ma tutti hanno la stessa chiamata di compressione che sta dando l'errore.Impossibile comprimere una bitmap riciclata

Questo è il codice che uso per salvare l'immagine:

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; 
    } 

E questo è il codice per salvarlo nella SDCard:

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()); 
} 

sto ottenendo l'errore:

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

risposta

13

Questo probabilmente sta causando il riciclo della bitmap:

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

Se si desidera che la bitmap si blocchi più a lungo, è necessario copiarla.

+0

Era quello! Ho tirato fuori quella linea e ha funzionato perfettamente! Grazie!!! – Lucia

+2

Non si dovrebbe prendere la linea; la bitmap fornita dalla cache può essere riciclata in qualsiasi momento dalla vista che la possiede. Hai davvero bisogno di prendere la tua copia di Bitmap usando 'Bitmap.copy()'. –

+0

Puoi spiegare come copiarlo? – Lucia

14

Questo ha risolto i miei problemi.

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. 
Problemi correlati