记录:
/**
* 1.获取和保存当前屏幕的截图
*/
private void GetandSaveCurrentImage()
{
//1.构建Bitmap
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Bitmap Bmp;
//2.获取屏幕
View decorview = this.getWindow().getDecorView();
decorview.setDrawingCacheEnabled(true);
Bmp = decorview.getDrawingCache();
// 获取状态栏高度
Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
Log.i("TAG", "" + statusBarHeight);
Bmp = Bitmap.createBitmap(Bmp, 0, statusBarHeight, width, height - statusBarHeight);
//保存图片
saveImageToGallery(this,Bmp,"share.png");
}
/**
* 2.保存图片到指定路径
*
* @param context
* @param bitmap 要保存的图片
* @param fileName 自定义图片名称 getString(R.string.app_name) + "" + System.currentTimeMillis()+".png"
* @return true 成功 false失败
*/
public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
// 保存图片至指定路径
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";
Log.i("info","路径"+storePath);
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
//通过io流的方式来压缩保存图片(80代表压缩20%)
boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
fos.flush();
fos.close();
//发送广播通知系统图库刷新数据
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
3.由于要对SDCard进行操作,所以别忘记了在manifest.xml文件中赋以对SDCard的读写权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
参考文章: