1.view转bitmap
/**
* View to bitmap.
*
* @param view The view.
* @return bitmap
*/
public static Bitmap view2Bitmap(final View view) {
if (view == null) return null;
Bitmap ret =
Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(ret);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null) {
bgDrawable.draw(canvas);
} else {
canvas.drawColor(Color.WHITE);
}
view.draw(canvas);
return ret;
}
2.保存bitmap到File
注意申请必要的文件读写权限
public static void bitmapToFile(Activity activity,Bitmap bitmap, File destFile) {
//替换为透明画布
Bitmap b = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
canvas.drawColor(Color.TRANSPARENT);
Paint paint = new Paint();
canvas.drawBitmap(bitmap, 0, 0, paint);
try {
FileOutputStream fout = new FileOutputStream(destFile);
BufferedOutputStream bos = new BufferedOutputStream(fout);
b.compress(Bitmap.CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (Exception e) {
Log.i("test","failed...");
}
//通知系统刷新媒体文件
activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(destFile)));
Log.i("test","success...");
}