android截屏:保存一个view的内容为图片并存放到SD卡

项目中偶尔会用到截屏分享,于是就有了下面这个截屏的方法~

下面得saveImage()方法就是保存当前Activity对应的屏幕所有内容的截屏保存。

private void saveImage() {

// SD卡保存路径

String savePath = Environment.getExternalStorageDirectory() + "/temp.png";

// showProgress("请稍候", "正在保存图片……");

saveMyBitmap(getBitmapFromRootView(getWindow().getDecorView()), savePath);

}

// 获取view并转换成bitmap图片

private static Bitmap getBitmapFromRootView(View view) {


view.setDrawingCacheEnabled(true);

Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache());

view.setDrawingCacheEnabled(false);

if (bmp != null) {

return bmp;

} else {

return null;

}

}

// 把bitmao图片保存到对应的SD卡路径中

private void saveMyBitmap(Bitmap mBitmap, String path) {

File f = new File(path);

try {

f.createNewFile();

} catch (IOException e) {

e.printStackTrace();

}

FileOutputStream fOut = null;

try {

fOut = new FileOutputStream(f);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

if (mBitmap != null) {

// 保存格式为PNG 质量为100

mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);

}

try {

fOut.flush();

} catch (IOException e) {

e.printStackTrace();

}

try {

fOut.close();

} catch (IOException e) {

e.printStackTrace();

}

}

原文地址:https://www.cnblogs.com/xgjblog/p/4033269.html