Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't compress a recycled bitmap

I'm trying to save a Layout into an Image in the SDCard but I get this error. I tried several codes I found in this forum but all of them have the same compress call that is giving the error.

This is the code I use for saving the image:

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

And this is the code for saving it in the 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());
}

I'm getting the error:

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

like image 395
Lucia Avatar asked Dec 13 '11 14:12

Lucia


People also ask

What does bitmap recycle do?

The recycle() method allows an app to reclaim memory as soon as possible. Caution: You should use recycle() only when you are sure that the bitmap is no longer being used. If you call recycle() and later attempt to draw the bitmap, you will get the error: "Canvas: trying to use a recycled bitmap" .

What is bitmap compress?

High colour photographic images need compression. Lossless compression preserves all picture information. Lossy compression creates much smaller files. Be careful when repeatedly editing lossy-format files.


2 Answers

This resolved my issues.

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.
like image 178
miroslavign Avatar answered Sep 27 '22 19:09

miroslavign


This is probably causing the bitmap to be recycled:

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

If you want the bitmap to hang around longer, then you should copy it.

like image 37
Graham Borland Avatar answered Sep 27 '22 17:09

Graham Borland