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!
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" .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With