View view = findViewById(R.id.preview);
Bitmap bitmap = null;
OutputStream stream = null;
boolean result = false;
try {
final String filename = "saved.jpg";
final File saved = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
final int quality = 100;
stream = new FileOutputStream(saved);
final boolean isAutoScale = false;
view.buildDrawingCache(isAutoScale);
bitmap = view.getDrawingCache(isAutoScale);
result = bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
view.destroyDrawingCache();
bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
Toast.makeText(getContext(), (result && saved.exists()) ? "Succeed." : "Failure.", Toast.LENGTH_SHORT).show();
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
try {
if (bitmap != null) {
bitmap.recycle();
}
if (stream != null) {
stream.close();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}