无法压缩已回收的位图

13

我正在尝试将一个布局保存为SD卡中的图像,但是我遇到了这个错误。我尝试了在这个论坛上找到的几个代码,但是所有的代码都有相同的压缩调用导致了这个错误。

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

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());
}
我遇到了这个错误:

在压缩调用中不能压缩已经回收的位图!

3个回答

20

这可能导致位图被回收:

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

如果你希望位图存在更久的时间,那么你应该将其复制。


2
你不应该删除这行代码;缓存提供的位图可能随时被拥有它的视图回收。你真的需要使用 Bitmap.copy() 复制自己的位图。 - Graham Borland
你能解释一下如何复制它吗? - Lucia
就像我说的,调用 Bitmap.copy()。这是文档:http://developer.android.com/reference/android/graphics/Bitmap.html#copy(android.graphics.Bitmap.Config, boolean) - Graham Borland
对我也起作用了,因为我只需要稍微将代码移动到方法下面一点就好了。我在Xamarin.Android中检查了我的代码,并且将其设置回false的时间太早了。 - DankMemester 'Andrew Servania'

19

这解决了我的问题。

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.

2
解决方案是:您只需要复制位图即可。
imageneViewer.setImageBitmap(lienzo.getDrawingCache().copy(Bitmap.Config.RGB_565, false));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接